(** * IndProp: Inductively Defined Propositions *)

Set Warnings "-notation-overridden,-parsing".
Require Export Logic.
Require Export Poly.
Require Coq.omega.Omega.

(* ################################################################# *)
(** * Inductively Defined Propositions *)

(** In the [Logic] chapter, we looked at several ways of writing
    propositions, including conjunction, disjunction, and quantifiers.
    In this chapter, we bring a new tool into the mix: _inductive
    definitions_. *)

(** Recall that we have seen two ways of stating that a number [n] is
    even: We can say (1) [evenb n = true], or (2) [exists k, n =
    double k].  Yet another possibility is to say that [n] is even if
    we can establish its evenness from the following rules:

       - Rule [ev_0]:  The number [0] is even.
       - Rule [ev_SS]: If [n] is even, then [S (S n)] is even. *)

(** To illustrate how this definition of evenness works, let's
    imagine using it to show that [4] is even. By rule [ev_SS], it
    suffices to show that [2] is even. This, in turn, is again
    guaranteed by rule [ev_SS], as long as we can show that [0] is
    even. But this last fact follows directly from the [ev_0] rule. *)

(** We will see many definitions like this one during the rest
    of the course.  For purposes of informal discussions, it is
    helpful to have a lightweight notation that makes them easy to
    read and write.  _Inference rules_ are one such notation: *)
(**

                              ------------                        (ev_0)
                                 ev 0

                                  ev n
                             --------------                      (ev_SS)
                              ev (S (S n))
*)

(** Each of the textual rules above is reformatted here as an
    inference rule; the intended reading is that, if the _premises_
    above the line all hold, then the _conclusion_ below the line
    follows.  For example, the rule [ev_SS] says that, if [n]
    satisfies [ev], then [S (S n)] also does.  If a rule has no
    premises above the line, then its conclusion holds
    unconditionally.

    We can represent a proof using these rules by combining rule
    applications into a _proof tree_. Here's how we might transcribe
    the above proof that [4] is even: *)
(**

                             ------  (ev_0)
                              ev 0
                             ------ (ev_SS)
                              ev 2
                             ------ (ev_SS)
                              ev 4
*)

(** Why call this a "tree" (rather than a "stack", for example)?
    Because, in general, inference rules can have multiple premises.
    We will see examples of this below. *)

(** Putting all of this together, we can translate the definition of
    evenness into a formal Coq definition using an [Inductive]
    declaration, where each constructor corresponds to an inference
    rule: *)

Inductive ev : nat -> Prop :=
| ev_0 : ev 0
| ev_SS : forall n : nat, ev n -> ev (S (S n)).

(** This definition is different in one crucial respect from
    previous uses of [Inductive]: its result is not a [Type], but
    rather a function from [nat] to [Prop] -- that is, a property of
    numbers.  Note that we've already seen other inductive definitions
    that result in functions, such as [list], whose type is [Type ->
    Type].  What is new here is that, because the [nat] argument of
    [ev] appears _unnamed_, to the _right_ of the colon, it is allowed
    to take different values in the types of different constructors:
    [0] in the type of [ev_0] and [S (S n)] in the type of [ev_SS].

    In contrast, the definition of [list] names the [X] parameter
    _globally_, to the _left_ of the colon, forcing the result of
    [nil] and [cons] to be the same ([list X]).  Had we tried to bring
    [nat] to the left in defining [ev], we would have seen an error: *)

Fail Inductive wrong_ev (n : nat) : Prop :=
| wrong_ev_0 : wrong_ev 0
| wrong_ev_SS : forall n, wrong_ev n -> wrong_ev (S (S n)).
(* ===> Error: A parameter of an inductive type n is not
        allowed to be used as a bound variable in the type
        of its constructor. *)

(** ("Parameter" here is Coq jargon for an argument on the left of the
    colon in an [Inductive] definition; "index" is used to refer to
    arguments on the right of the colon.) *)

(** We can think of the definition of [ev] as defining a Coq property
    [ev : nat -> Prop], together with primitive theorems [ev_0 : ev 0] and
    [ev_SS : forall n, ev n -> ev (S (S n))]. *)

(** Such "constructor theorems" have the same status as proven
    theorems.  In particular, we can use Coq's [apply] tactic with the
    rule names to prove [ev] for particular numbers... *)

Theorem ev_4 : ev 4.
Proof. apply ev_SS. apply ev_SS. apply ev_0. Qed.

(** ... or we can use function application syntax: *)

Theorem ev_4' : ev 4.
Proof. apply (ev_SS 2 (ev_SS 0 ev_0)). Qed.

(** We can also prove theorems that have hypotheses involving [ev]. *)

Theorem ev_plus4 : forall n, ev n -> ev (4 + n).
Proof.
  intros n. simpl. intros Hn.
  apply ev_SS. apply ev_SS. apply Hn.
Qed.

(** More generally, we can show that any number multiplied by 2 is even: *)

(** **** Exercise: 1 star (ev_double)  *)
Theorem ev_double : forall n,
  ev (double n).
Proof.
induction n.
-  simpl. apply ev_0.
-  simpl. apply ev_SS. apply IHn.
Qed.
(** [] *)

(* ################################################################# *)
(** * Using Evidence in Proofs *)

(** Besides _constructing_ evidence that numbers are even, we can also
    _reason about_ such evidence.

    Introducing [ev] with an [Inductive] declaration tells Coq not
    only that the constructors [ev_0] and [ev_SS] are valid ways to
    build evidence that some number is even, but also that these two
    constructors are the _only_ ways to build evidence that numbers
    are even (in the sense of [ev]). *)

(** In other words, if someone gives us evidence [E] for the assertion
    [ev n], then we know that [E] must have one of two shapes:

      - [E] is [ev_0] (and [n] is [O]), or
      - [E] is [ev_SS n' E'] (and [n] is [S (S n')], where [E'] is
        evidence for [ev n']). *)

(** This suggests that it should be possible to analyze a hypothesis
    of the form [ev n] much as we do inductively defined data
    structures; in particular, it should be possible to argue by
    _induction_ and _case analysis_ on such evidence.  Let's look at a
    few examples to see what this means in practice. *)

(* ================================================================= *)
(** ** Inversion on Evidence *)

(** Suppose we are proving some fact involving a number [n], and we
    are given [ev n] as a hypothesis.  We already know how to perform
    case analysis on [n] using the [inversion] tactic, generating
    separate subgoals for the case where [n = O] and the case where [n
    = S n'] for some [n'].  But for some proofs we may instead want to
    analyze the evidence that [ev n] _directly_.

    By the definition of [ev], there are two cases to consider:

    - If the evidence is of the form [ev_0], we know that [n = 0].

    - Otherwise, the evidence must have the form [ev_SS n' E'], where
      [n = S (S n')] and [E'] is evidence for [ev n']. *)

(** We can perform this kind of reasoning in Coq, again using
    the [inversion] tactic.  Besides allowing us to reason about
    equalities involving constructors, [inversion] provides a
    case-analysis principle for inductively defined propositions.
    When used in this way, its syntax is similar to [destruct]: We
    pass it a list of identifiers separated by [|] characters to name
    the arguments to each of the possible constructors.  *)

Theorem ev_minus2 : forall n,
  ev n -> ev (pred (pred n)).
Proof.
  intros n E.
  inversion E as [| n' E'].
  - (* E = ev_0 *) simpl. apply ev_0.
  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.

(** In words, here is how the inversion reasoning works in this proof:

    - If the evidence is of the form [ev_0], we know that [n = 0].
      Therefore, it suffices to show that [ev (pred (pred 0))] holds.
      By the definition of [pred], this is equivalent to showing that
      [ev 0] holds, which directly follows from [ev_0].

    - Otherwise, the evidence must have the form [ev_SS n' E'], where
      [n = S (S n')] and [E'] is evidence for [ev n'].  We must then
      show that [ev (pred (pred (S (S n'))))] holds, which, after
      simplification, follows directly from [E']. *)

(** This particular proof also works if we replace [inversion] by
    [destruct]: *)

Theorem ev_minus2' : forall n,
  ev n -> ev (pred (pred n)).
Proof.
  intros n E.
  destruct E as [| n' E'].
  - (* E = ev_0 *) simpl. apply ev_0.
  - (* E = ev_SS n' E' *) simpl. apply E'.  Qed.

(** The difference between the two forms is that [inversion] is more
    convenient when used on a hypothesis that consists of an inductive
    property applied to a complex expression (as opposed to a single
    variable).  Here's is a concrete example.  Suppose that we wanted
    to prove the following variation of [ev_minus2]: *)

Theorem evSS_ev : forall n,
  ev (S (S n)) -> ev n.

(** Intuitively, we know that evidence for the hypothesis cannot
    consist just of the [ev_0] constructor, since [O] and [S] are
    different constructors of the type [nat]; hence, [ev_SS] is the
    only case that applies.  Unfortunately, [destruct] is not smart
    enough to realize this, and it still generates two subgoals.  Even
    worse, in doing so, it keeps the final goal unchanged, failing to
    provide any useful information for completing the proof.  *)

Proof.
  intros n E.
  destruct E as [| n' E'].
  - (* E = ev_0. *)
    (* We must prove that [n] is even from no assumptions! *)
Abort.

(** What happened, exactly?  Calling [destruct] has the effect of
    replacing all occurrences of the property argument by the values
    that correspond to each constructor.  This is enough in the case
    of [ev_minus2'] because that argument, [n], is mentioned directly
    in the final goal. However, it doesn't help in the case of
    [evSS_ev] since the term that gets replaced ([S (S n)]) is not
    mentioned anywhere. *)

(** The [inversion] tactic, on the other hand, can detect (1) that the
    first case does not apply, and (2) that the [n'] that appears on
    the [ev_SS] case must be the same as [n].  This allows us to
    complete the proof: *)

Theorem evSS_ev : forall n,
  ev (S (S n)) -> ev n.
Proof.
  intros n E.
  inversion E as [| n' E'].
  (* We are in the [E = ev_SS n' E'] case now. *)
  apply E'.
Qed.

(** By using [inversion], we can also apply the principle of explosion
    to "obviously contradictory" hypotheses involving inductive
    properties. For example: *)

Theorem one_not_even : ~ ev 1.
Proof.
  intros H. inversion H. Qed.

(** **** Exercise: 1 star (SSSSev__even)  *)
(** Prove the following result using [inversion]. *)

Theorem SSSSev__even : forall n,
  ev (S (S (S (S n)))) -> ev n.
Proof.
intros n H.
inversion H.
apply evSS_ev in H1.
exact H1.
Qed.
(** [] *)

(** **** Exercise: 1 star (even5_nonsense)  *)
(** Prove the following result using [inversion]. *)

Theorem even5_nonsense :
  ev 5 -> 2 + 2 = 9.
Proof.
intros contra. inversion contra. inversion H0. inversion H2.
Qed.
(** [] *)

(** The way we've used [inversion] here may seem a bit
    mysterious at first.  Until now, we've only used [inversion] on
    equality propositions, to utilize injectivity of constructors or
    to discriminate between different constructors.  But we see here
    that [inversion] can also be applied to analyzing evidence for
    inductively defined propositions.

    Here's how [inversion] works in general.  Suppose the name [I]
    refers to an assumption [P] in the current context, where [P] has
    been defined by an [Inductive] declaration.  Then, for each of the
    constructors of [P], [inversion I] generates a subgoal in which
    [I] has been replaced by the exact, specific conditions under
    which this constructor could have been used to prove [P].  Some of
    these subgoals will be self-contradictory; [inversion] throws
    these away.  The ones that are left represent the cases that must
    be proved to establish the original goal.  For those, [inversion]
    adds all equations into the proof context that must hold of the
    arguments given to [P] (e.g., [S (S n') = n] in the proof of
    [evSS_ev]). *)

(** The [ev_double] exercise above shows that our new notion of
    evenness is implied by the two earlier ones (since, by
    [even_bool_prop] in chapter [Logic], we already know that
    those are equivalent to each other). To show that all three
    coincide, we just need the following lemma: *)

Lemma ev_even_firsttry : forall n,
  ev n -> exists k, n = double k.
Proof.
(* WORKED IN CLASS *)

(** We could try to proceed by case analysis or induction on [n].  But
    since [ev] is mentioned in a premise, this strategy would probably
    lead to a dead end, as in the previous section.  Thus, it seems
    better to first try inversion on the evidence for [ev].  Indeed,
    the first case can be solved trivially. *)

  intros n E. inversion E as [| n' E'].
  - (* E = ev_0 *)
    exists 0. reflexivity.
  - (* E = ev_SS n' E' *) simpl.

(** Unfortunately, the second case is harder.  We need to show [exists
    k, S (S n') = double k], but the only available assumption is
    [E'], which states that [ev n'] holds.  Since this isn't directly
    useful, it seems that we are stuck and that performing case
    analysis on [E] was a waste of time.

    If we look more closely at our second goal, however, we can see
    that something interesting happened: By performing case analysis
    on [E], we were able to reduce the original result to an similar
    one that involves a _different_ piece of evidence for [ev]: [E'].
    More formally, we can finish our proof by showing that

        exists k', n' = double k',

    which is the same as the original statement, but with [n'] instead
    of [n].  Indeed, it is not difficult to convince Coq that this
    intermediate result suffices. *)

    assert (I : (exists k', n' = double k') ->
                (exists k, S (S n') = double k)).
    { intros [k' Hk']. rewrite Hk'. exists (S k'). simpl. reflexivity. }
    apply I. (* reduce the original goal to the new one *)

Admitted.

(* ================================================================= *)
(** ** Induction on Evidence *)

(** If this looks familiar, it is no coincidence: We've encountered
    similar problems in the [Induction] chapter, when trying to use
    case analysis to prove results that required induction.  And once
    again the solution is... induction!

    The behavior of [induction] on evidence is the same as its
    behavior on data: It causes Coq to generate one subgoal for each
    constructor that could have used to build that evidence, while
    providing an induction hypotheses for each recursive occurrence of
    the property in question. *)

(** Let's try our current lemma again: *)

Lemma ev_even : forall n,
  ev n -> exists k, n = double k.
Proof.
  intros n E.
  induction E as [|n' E' IH].
  - (* E = ev_0 *)
    exists 0. reflexivity.
  - (* E = ev_SS n' E'
       with IH : exists k', n' = double k' *)
    destruct IH as [k' Hk'].
    rewrite Hk'. exists (S k'). reflexivity.
Qed.

(** Here, we can see that Coq produced an [IH] that corresponds to
    [E'], the single recursive occurrence of [ev] in its own
    definition.  Since [E'] mentions [n'], the induction hypothesis
    talks about [n'], as opposed to [n] or some other number. *)

(** The equivalence between the second and third definitions of
    evenness now follows. *)

Theorem ev_even_iff : forall n,
  ev n <-> exists k, n = double k.
Proof.
  intros n. split.
  - (* -> *) apply ev_even.
  - (* <- *) intros [k Hk]. rewrite Hk. apply ev_double.
Qed.

(** As we will see in later chapters, induction on evidence is a
    recurring technique across many areas, and in particular when
    formalizing the semantics of programming languages, where many
    properties of interest are defined inductively. *)

(** The following exercises provide simple examples of this
    technique, to help you familiarize yourself with it. *)

(** **** Exercise: 2 stars (ev_sum)  *)
Theorem ev_sum : forall n m, ev n -> ev m -> ev (n + m).
Proof.
intros n m H1 H2.
induction H1.
simpl. exact H2.
simpl. apply ev_SS. exact IHev.
Qed.
(** [] *)

(** **** Exercise: 4 stars, advanced, optional (ev'_ev)  *)
(** In general, there may be multiple ways of defining a
    property inductively.  For example, here's a (slightly contrived)
    alternative definition for [ev]: *)

Inductive ev' : nat -> Prop :=
| ev'_0 : ev' 0
| ev'_2 : ev' 2
| ev'_sum : forall n m, ev' n -> ev' m -> ev' (n + m).

(** Prove that this definition is logically equivalent to the old
    one.  (You may want to look at the previous theorem when you get
    to the induction step.) *)

Theorem ev'_ev : forall n, ev' n <-> ev n.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, recommended (ev_ev__ev)  *)
(** Finding the appropriate thing to do induction on is a
    bit tricky here: *)

Theorem ev_ev__ev : forall n m,
  ev (n+m) -> ev n -> ev m.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (ev_plus_plus)  *)
(** This exercise just requires applying existing lemmas.  No
    induction or even case analysis is needed, though some of the
    rewriting may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  ev (n+m) -> ev (n+p) -> ev (m+p).
Proof.
(* FILL IN HERE *)
Admitted.
(** [] *)

(* ################################################################# *)
(** * Inductive Relations *)

(** A proposition parameterized by a number (such as [ev])
    can be thought of as a _property_ -- i.e., it defines
    a subset of [nat], namely those numbers for which the proposition
    is provable.  In the same way, a two-argument proposition can be
    thought of as a _relation_ -- i.e., it defines a set of pairs for
    which the proposition is provable. *)

Module Playground.

(** One useful example is the "less than or equal to" relation on
    numbers. *)

(** The following definition should be fairly intuitive.  It
    says that there are two ways to give evidence that one number is
    less than or equal to another: either observe that they are the
    same number, or give evidence that the first is less than or equal
    to the predecessor of the second. *)

Inductive le : nat -> nat -> Prop :=
  | le_n : forall n, le n n
  | le_S : forall n m, (le n m) -> (le n (S m)).

Notation "m <= n" := (le m n).

(** Proofs of facts about [<=] using the constructors [le_n] and
    [le_S] follow the same patterns as proofs about properties, like
    [ev] above. We can [apply] the constructors to prove [<=]
    goals (e.g., to show that [3<=3] or [3<=6]), and we can use
    tactics like [inversion] to extract information from [<=]
    hypotheses in the context (e.g., to prove that [(2 <= 1) ->
    2+2=5].) *)

(** Here are some sanity checks on the definition.  (Notice that,
    although these are the same kind of simple "unit tests" as we gave
    for the testing functions we wrote in the first few lectures, we
    must construct their proofs explicitly -- [simpl] and
    [reflexivity] don't do the job, because the proofs aren't just a
    matter of simplifying computations.) *)

Theorem test_le1 :
  3 <= 3.
Proof.
  (* WORKED IN CLASS *)
  apply le_n.  Qed.

Theorem test_le2 :
  3 <= 6.
Proof.
  (* WORKED IN CLASS *)
  apply le_S. apply le_S. apply le_S. apply le_n.  Qed.

Theorem test_le3 :
  (2 <= 1) -> 2 + 2 = 5.
Proof.
  (* WORKED IN CLASS *)
  intros H. inversion H. inversion H2.  Qed.

(** The "strictly less than" relation [n < m] can now be defined
    in terms of [le]. *)

End Playground.

Definition lt (n m:nat) := le (S n) m.

Notation "m < n" := (lt m n).

(** Here are a few more simple relations on numbers: *)

Inductive square_of : nat -> nat -> Prop :=
  | sq : forall n:nat, square_of n (n * n).

Inductive next_nat : nat -> nat -> Prop :=
  | nn : forall n:nat, next_nat n (S n).

Inductive next_even : nat -> nat -> Prop :=
  | ne_1 : forall n, ev (S n) -> next_even n (S n)
  | ne_2 : forall n, ev (S (S n)) -> next_even n (S (S n)).

(** **** Exercise: 2 stars, optional (total_relation)  *)
(** Define an inductive binary relation [total_relation] that holds
    between every pair of natural numbers. *)

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

(** **** Exercise: 2 stars, optional (empty_relation)  *)
(** Define an inductive binary relation [empty_relation] (on numbers)
    that never holds. *)

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

(** **** Exercise: 3 stars, optional (le_exercises)  *)
(** Here are a number of facts about the [<=] and [<] relations that
    we are going to need later in the course.  The proofs make good
    practice exercises. *)

Lemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.
Proof.
intros m n o H1 H2.
rewrite <- H1 in H2.
exact H2.
Qed.

Theorem O_le_n : forall n,
  0 <= n.
Proof.
induction n.
apply le_n.
apply le_S.
exact IHn.
Qed.

Theorem n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m.
Proof.
intros n m H.
rewrite <- PeanoNat.Nat.add_1_r.
rewrite <- PeanoNat.Nat.add_1_r with m.
apply Plus.plus_le_compat_r.
exact H.
Qed.

Theorem Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
intros n m H.
rewrite <- PeanoNat.Nat.add_1_r in H.
rewrite <- PeanoNat.Nat.add_1_r with m in H.
apply Plus.plus_le_reg_l with (p:=1).
rewrite plus_comm.
rewrite plus_comm with (m:=m).
exact H.
Qed.

Theorem le_plus_l : forall a b,
  a <= a + b.
Proof.
intros a b.
Search (le ?a (?a + ?b)).
apply Plus.le_plus_l.
Qed.

Theorem plus_lt : forall n1 n2 m,
  n1 + n2 < m ->
  n1 < m /\ n2 < m.
Proof.
unfold lt.
intros n1 n2 m H.
split.
-
rewrite <- PeanoNat.Nat.add_succ_l in H.
rewrite le_plus_l with (b:=n2).
exact H.
-
rewrite <- PeanoNat.Nat.add_succ_r in H.
rewrite le_plus_l with (b:=n1).
rewrite plus_comm.
exact H.
Qed.

Theorem lt_S : forall n m,
  n < m ->
  n < S m.
Proof.
unfold lt.
intros n m H.
rewrite <- PeanoNat.Nat.add_1_l with (n:=m).
rewrite plus_comm.
rewrite <- le_plus_l.
exact H.
Qed.

Theorem leb_complete : forall n m,
  leb n m = true -> n <= m.
Proof.
induction n.
-
induction m.
+ reflexivity.
+ intros H. apply O_le_n.
-
induction m.
+ intros H. inversion H.
+ intros H. inversion H. apply IHn in H1. apply le_n_S in H1. exact H1.
Qed.

(** Hint: The next one may be easiest to prove by induction on [m]. *)

Theorem leb_correct : forall n m,
  n <= m ->
  leb n m = true.
Proof.
(* FILL IN HERE *) Admitted.

(** Hint: This theorem can easily be proved without using [induction]. *)

Theorem leb_true_trans : forall n m o,
  leb n m = true -> leb m o = true -> leb n o = true.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, optional (leb_iff)  *)
Theorem leb_iff : forall n m,
  leb n m = true <-> n <= m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

Module R.

(** **** Exercise: 3 stars, recommended (R_provability)  *)
(** We can define three-place relations, four-place relations,
    etc., in just the same way as binary relations.  For example,
    consider the following three-place relation on numbers: *)

Inductive R : nat -> nat -> nat -> Prop :=
   | c1 : R 0 0 0
   | c2 : forall m n o, R m n o -> R (S m) n (S o)
   | c3 : forall m n o, R m n o -> R m (S n) (S o)
   | c4 : forall m n o, R (S m) (S n) (S (S o)) -> R m n o
   | c5 : forall m n o, R m n o -> R n m o.

(** - Which of the following propositions are provable?
      - [R 1 1 2]
      - [R 2 2 6]

    - If we dropped constructor [c5] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

    - If we dropped constructor [c4] from the definition of [R],
      would the set of provable propositions change?  Briefly (1
      sentence) explain your answer.

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

(** **** Exercise: 3 stars, optional (R_fact)  *)
(** The relation [R] above actually encodes a familiar function.
    Figure out which function; then state and prove this equivalence
    in Coq? *)

Definition fR : nat -> nat -> nat
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Theorem R_equiv_fR : forall m n o, R m n o <-> fR m n = o.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

End R.

(** **** Exercise: 4 stars, advanced (subsequence)  *)
(** A list is a _subsequence_ of another list if all of the elements
    in the first list occur in the same order in the second list,
    possibly with some extra elements in between. For example,

      [1;2;3]

    is a subsequence of each of the lists

      [1;2;3]
      [1;1;1;2;2;3]
      [1;2;7;3]
      [5;6;1;9;9;2;7;3;8]

    but it is _not_ a subsequence of any of the lists

      [1;2]
      [1;3]
      [5;6;2;1;7;3;8].

    - Define an inductive proposition [subseq] on [list nat] that
      captures what it means to be a subsequence. (Hint: You'll need
      three cases.)

    - Prove [subseq_refl] that subsequence is reflexive, that is,
      any list is a subsequence of itself.

    - Prove [subseq_app] that for any lists [l1], [l2], and [l3],
      if [l1] is a subsequence of [l2], then [l1] is also a subsequence
      of [l2 ++ l3].

    - (Optional, harder) Prove [subseq_trans] that subsequence is
      transitive -- that is, if [l1] is a subsequence of [l2] and [l2]
      is a subsequence of [l3], then [l1] is a subsequence of [l3].
      Hint: choose your induction carefully! *)

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

(** **** Exercise: 2 stars, optional (R_provability2)  *)
(** Suppose we give Coq the following definition:

    Inductive R : nat -> list nat -> Prop :=
      | c1 : R 0 []
      | c2 : forall n l, R n l -> R (S n) (n :: l)
      | c3 : forall n l, R (S n) l -> R n l.

    Which of the following propositions are provable?

    - [R 2 [1;0]]
    - [R 1 [1;2;1;0]]
    - [R 6 [3;2;1;0]]  *)

(** [] *)

(* ################################################################# *)
(** * Case Study: Regular Expressions *)

(** The [ev] property provides a simple example for illustrating
    inductive definitions and the basic techniques for reasoning about
    them, but it is not terribly exciting -- after all, it is
    equivalent to the two non-inductive definitions of evenness that
    we had already seen, and does not seem to offer any concrete
    benefit over them.  To give a better sense of the power of
    inductive definitions, we now show how to use them to model a
    classic concept in computer science: _regular expressions_. *)

(** Regular expressions are a simple language for describing strings,
    defined as follows: *)

Inductive reg_exp {T : Type} : Type :=
| EmptySet : reg_exp
| EmptyStr : reg_exp
| Char : T -> reg_exp
| App : reg_exp -> reg_exp -> reg_exp
| Union : reg_exp -> reg_exp -> reg_exp
| Star : reg_exp -> reg_exp.

(** Note that this definition is _polymorphic_: Regular
    expressions in [reg_exp T] describe strings with characters drawn
    from [T] -- that is, lists of elements of [T].

    (We depart slightly from standard practice in that we do not
    require the type [T] to be finite.  This results in a somewhat
    different theory of regular expressions, but the difference is not
    significant for our purposes.) *)

(** We connect regular expressions and strings via the following
    rules, which define when a regular expression _matches_ some
    string:

      - The expression [EmptySet] does not match any string.

      - The expression [EmptyStr] matches the empty string [[]].

      - The expression [Char x] matches the one-character string [[x]].

      - If [re1] matches [s1], and [re2] matches [s2], then [App re1
        re2] matches [s1 ++ s2].

      - If at least one of [re1] and [re2] matches [s], then [Union re1
        re2] matches [s].

      - Finally, if we can write some string [s] as the concatenation of
        a sequence of strings [s = s_1 ++ ... ++ s_k], and the
        expression [re] matches each one of the strings [s_i], then
        [Star re] matches [s].

        As a special case, the sequence of strings may be empty, so
        [Star re] always matches the empty string [[]] no matter what
        [re] is. *)

(** We can easily translate this informal definition into an
    [Inductive] one as follows: *)

Inductive exp_match {T} : list T -> reg_exp -> Prop :=
| MEmpty : exp_match [] EmptyStr
| MChar : forall x, exp_match [x] (Char x)
| MApp : forall s1 re1 s2 re2,
           exp_match s1 re1 ->
           exp_match s2 re2 ->
           exp_match (s1 ++ s2) (App re1 re2)
| MUnionL : forall s1 re1 re2,
              exp_match s1 re1 ->
              exp_match s1 (Union re1 re2)
| MUnionR : forall re1 s2 re2,
              exp_match s2 re2 ->
              exp_match s2 (Union re1 re2)
| MStar0 : forall re, exp_match [] (Star re)
| MStarApp : forall s1 s2 re,
               exp_match s1 re ->
               exp_match s2 (Star re) ->
               exp_match (s1 ++ s2) (Star re).

(** Again, for readability, we can also display this definition using
    inference-rule notation.  At the same time, let's introduce a more
    readable infix notation. *)

Notation "s =~ re" := (exp_match s re) (at level 80).

(**

                          ----------------                    (MEmpty)
                           [] =~ EmptyStr

                          ---------------                      (MChar)
                           [x] =~ Char x

                       s1 =~ re1    s2 =~ re2
                      -------------------------                 (MApp)
                       s1 ++ s2 =~ App re1 re2

                              s1 =~ re1
                        ---------------------                (MUnionL)
                         s1 =~ Union re1 re2

                              s2 =~ re2
                        ---------------------                (MUnionR)
                         s2 =~ Union re1 re2

                          ---------------                     (MStar0)
                           [] =~ Star re

                      s1 =~ re    s2 =~ Star re
                     ---------------------------            (MStarApp)
                        s1 ++ s2 =~ Star re
*)

(** Notice that these rules are not _quite_ the same as the informal
    ones that we gave at the beginning of the section.  First, we
    don't need to include a rule explicitly stating that no string
    matches [EmptySet]; we just don't happen to include any rule that
    would have the effect of some string matching [EmptySet].  (Indeed,
    the syntax of inductive definitions doesn't even _allow_ us to
    give such a "negative rule.")

    Second, the informal rules for [Union] and [Star] correspond
    to two constructors each: [MUnionL] / [MUnionR], and [MStar0] /
    [MStarApp].  The result is logically equivalent to the original
    rules but more convenient to use in Coq, since the recursive
    occurrences of [exp_match] are given as direct arguments to the
    constructors, making it easier to perform induction on evidence.
    (The [exp_match_ex1] and [exp_match_ex2] exercises below ask you
    to prove that the constructors given in the inductive declaration
    and the ones that would arise from a more literal transcription of
    the informal rules are indeed equivalent.)

    Let's illustrate these rules with a few examples. *)

Example reg_exp_ex1 : [1] =~ Char 1.
Proof.
  apply MChar.
Qed.

Example reg_exp_ex2 : [1; 2] =~ App (Char 1) (Char 2).
Proof.
  apply (MApp [1] _ [2]).
  - apply MChar.
  - apply MChar.
Qed.

(** (Notice how the last example applies [MApp] to the strings [[1]]
    and [[2]] directly.  Since the goal mentions [[1; 2]] instead of
    [[1] ++ [2]], Coq wouldn't be able to figure out how to split the
    string on its own.)

    Using [inversion], we can also show that certain strings do _not_
    match a regular expression: *)

Example reg_exp_ex3 : ~ ([1; 2] =~ Char 1).
Proof.
  intros H. inversion H.
Qed.

(** We can define helper functions for writing down regular
    expressions. The [reg_exp_of_list] function constructs a regular
    expression that matches exactly the list that it receives as an
    argument: *)

Fixpoint reg_exp_of_list {T} (l : list T) :=
  match l with
  | [] => EmptyStr
  | x :: l' => App (Char x) (reg_exp_of_list l')
  end.

Example reg_exp_ex4 : [1; 2; 3] =~ reg_exp_of_list [1; 2; 3].
Proof.
  simpl. apply (MApp [1]).
  { apply MChar. }
  apply (MApp [2]).
  { apply MChar. }
  apply (MApp [3]).
  { apply MChar. }
  apply MEmpty.
Qed.

(** We can also prove general facts about [exp_match].  For instance,
    the following lemma shows that every string [s] that matches [re]
    also matches [Star re]. *)

Lemma MStar1 :
  forall T s (re : @reg_exp T) ,
    s =~ re ->
    s =~ Star re.
Proof.
  intros T s re H.
  rewrite <- (app_nil_r _ s).
  apply (MStarApp s [] re).
  - apply H.
  - apply MStar0.
Qed.

(** (Note the use of [app_nil_r] to change the goal of the theorem to
    exactly the same shape expected by [MStarApp].) *)

(** **** Exercise: 3 stars (exp_match_ex1)  *)
(** The following lemmas show that the informal matching rules given
    at the beginning of the chapter can be obtained from the formal
    inductive definition. *)

Lemma empty_is_empty : forall T (s : list T),
  ~ (s =~ EmptySet).
Proof.
unfold not.
intros T s H.
inversion H.
Qed.

Lemma MUnion' : forall T (s : list T) (re1 re2 : @reg_exp T),
  s =~ re1 \/ s =~ re2 ->
  s =~ Union re1 re2.
Proof.
intros T s re1 re2 H.
destruct H.
- apply MUnionL. exact H.
- apply MUnionR. exact H.
Qed.

(** The next lemma is stated in terms of the [fold] function from the
    [Poly] chapter: If [ss : list (list T)] represents a sequence of
    strings [s1, ..., sn], then [fold app ss []] is the result of
    concatenating them all together. *)

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

Lemma MStar' : forall T (ss : list (list T)) (re : reg_exp),
  (forall s, In s ss -> s =~ re) ->
  fold app ss [] =~ Star re.
Proof.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, optional (reg_exp_of_list_spec)  *)
(** Prove that [reg_exp_of_list] satisfies the following
    specification: *)

Lemma reg_exp_of_list_spec : forall T (s1 s2 : list T),
  s1 =~ reg_exp_of_list s2 <-> s1 = s2.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** Since the definition of [exp_match] has a recursive
    structure, we might expect that proofs involving regular
    expressions will often require induction on evidence. *)

(** For example, suppose that we wanted to prove the following
    intuitive result: If a regular expression [re] matches some string
    [s], then all elements of [s] must occur as character literals
    somewhere in [re].

    To state this theorem, we first define a function [re_chars] that
    lists all characters that occur in a regular expression: *)

Fixpoint re_chars {T} (re : reg_exp) : list T :=
  match re with
  | EmptySet => []
  | EmptyStr => []
  | Char x => [x]
  | App re1 re2 => re_chars re1 ++ re_chars re2
  | Union re1 re2 => re_chars re1 ++ re_chars re2
  | Star re => re_chars re
  end.

(** We can then phrase our theorem as follows: *)

Theorem in_re_match : forall T (s : list T) (re : reg_exp) (x : T),
  s =~ re ->
  In x s ->
  In x (re_chars re).
Proof.
  intros T s re x Hmatch Hin.
  induction Hmatch
    as [| x'
        | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2
        | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH
        | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2].
  (* WORKED IN CLASS *)
  - (* MEmpty *)
    apply Hin.
  - (* MChar *)
    apply Hin.
  - simpl. rewrite In_app_iff in *.
    destruct Hin as [Hin | Hin].
    + (* In x s1 *)
      left. apply (IH1 Hin).
    + (* In x s2 *)
      right. apply (IH2 Hin).
  - (* MUnionL *)
    simpl. rewrite In_app_iff.
    left. apply (IH Hin).
  - (* MUnionR *)
    simpl. rewrite In_app_iff.
    right. apply (IH Hin).
  - (* MStar0 *)
    destruct Hin.

(** Something interesting happens in the [MStarApp] case.  We obtain
    _two_ induction hypotheses: One that applies when [x] occurs in
    [s1] (which matches [re]), and a second one that applies when [x]
    occurs in [s2] (which matches [Star re]).  This is a good
    illustration of why we need induction on evidence for [exp_match],
    as opposed to [re]: The latter would only provide an induction
    hypothesis for strings that match [re], which would not allow us
    to reason about the case [In x s2]. *)

  - (* MStarApp *)
    simpl. rewrite In_app_iff in Hin.
    destruct Hin as [Hin | Hin].
    + (* In x s1 *)
      apply (IH1 Hin).
    + (* In x s2 *)
      apply (IH2 Hin).
Qed.

(** **** Exercise: 4 stars (re_not_empty)  *)
(** Write a recursive function [re_not_empty] that tests whether a
    regular expression matches some string. Prove that your function
    is correct. *)

Fixpoint re_not_empty {T : Type} (re : @reg_exp T) : bool
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Lemma re_not_empty_correct : forall T (re : @reg_exp T),
  (exists s, s =~ re) <-> re_not_empty re = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ================================================================= *)
(** ** The [remember] Tactic *)

(** One potentially confusing feature of the [induction] tactic is
    that it happily lets you try to set up an induction over a term
    that isn't sufficiently general.  The effect of this is to lose
    information (much as [destruct] can do), and leave you unable to
    complete the proof.  Here's an example: *)

Lemma star_app: forall T (s1 s2 : list T) (re : @reg_exp T),
  s1 =~ Star re ->
  s2 =~ Star re ->
  s1 ++ s2 =~ Star re.
Proof.
  intros T s1 s2 re H1.

(** Just doing an [inversion] on [H1] won't get us very far in
    the recursive cases. (Try it!). So we need induction (on
    evidence!). Here is a naive first attempt: *)

  induction H1
    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2
        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH
        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].

(** But now, although we get seven cases (as we would expect from the
    definition of [exp_match]), we have lost a very important bit of
    information from [H1]: the fact that [s1] matched something of the
    form [Star re].  This means that we have to give proofs for _all_
    seven constructors of this definition, even though all but two of
    them ([MStar0] and [MStarApp]) are contradictory.  We can still
    get the proof to go through for a few constructors, such as
    [MEmpty]... *)

  - (* MEmpty *)
    simpl. intros H. apply H.

(** ... but most cases get stuck.  For [MChar], for instance, we
    must show that

    s2 =~ Char x' -> x' :: s2 =~ Char x',

    which is clearly impossible. *)

  - (* MChar. Stuck... *)
Abort.

(** The problem is that [induction] over a Prop hypothesis only works
    properly with hypotheses that are completely general, i.e., ones
    in which all the arguments are variables, as opposed to more
    complex expressions, such as [Star re].

    (In this respect, [induction] on evidence behaves more like
    [destruct] than like [inversion].)

    We can solve this problem by generalizing over the problematic
    expressions with an explicit equality: *)

Lemma star_app: forall T (s1 s2 : list T) (re re' : reg_exp),
  re' = Star re ->
  s1 =~ re' ->
  s2 =~ Star re ->
  s1 ++ s2 =~ Star re.

(** We can now proceed by performing induction over evidence directly,
    because the argument to the first hypothesis is sufficiently
    general, which means that we can discharge most cases by inverting
    the [re' = Star re] equality in the context.

    This idiom is so common that Coq provides a tactic to
    automatically generate such equations for us, avoiding thus the
    need for changing the statements of our theorems. *)

Abort.

(** Invoking the tactic [remember e as x] causes Coq to (1) replace
    all occurrences of the expression [e] by the variable [x], and (2)
    add an equation [x = e] to the context.  Here's how we can use it
    to show the above result: *)

Lemma star_app: forall T (s1 s2 : list T) (re : reg_exp),
  s1 =~ Star re ->
  s2 =~ Star re ->
  s1 ++ s2 =~ Star re.
Proof.
  intros T s1 s2 re H1.
  remember (Star re) as re'.

(** We now have [Heqre' : re' = Star re]. *)

  generalize dependent s2.
  induction H1
    as [|x'|s1 re1 s2' re2 Hmatch1 IH1 Hmatch2 IH2
        |s1 re1 re2 Hmatch IH|re1 s2' re2 Hmatch IH
        |re''|s1 s2' re'' Hmatch1 IH1 Hmatch2 IH2].

(** The [Heqre'] is contradictory in most cases, which allows us to
    conclude immediately. *)

  - (* MEmpty *)  inversion Heqre'.
  - (* MChar *)   inversion Heqre'.
  - (* MApp *)    inversion Heqre'.
  - (* MUnionL *) inversion Heqre'.
  - (* MUnionR *) inversion Heqre'.

(** The interesting cases are those that correspond to [Star].  Note
    that the induction hypothesis [IH2] on the [MStarApp] case
    mentions an additional premise [Star re'' = Star re'], which
    results from the equality generated by [remember]. *)

  - (* MStar0 *)
    inversion Heqre'. intros s H. apply H.

  - (* MStarApp *)
    inversion Heqre'. rewrite H0 in IH2, Hmatch1.
    intros s2 H1. rewrite <- app_assoc.
    apply MStarApp.
    + apply Hmatch1.
    + apply IH2.
      * reflexivity.
      * apply H1.
Qed.

(** **** Exercise: 4 stars, optional (exp_match_ex2)  *)

(** The [MStar''] lemma below (combined with its converse, the
    [MStar'] exercise above), shows that our definition of [exp_match]
    for [Star] is equivalent to the informal one given previously. *)

Lemma MStar'' : forall T (s : list T) (re : reg_exp),
  s =~ Star re ->
  exists ss : list (list T),
    s = fold app ss []
    /\ forall s', In s' ss -> s' =~ re.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 5 stars, advanced (pumping)  *)
(** One of the first really interesting theorems in the theory of
    regular expressions is the so-called _pumping lemma_, which
    states, informally, that any sufficiently long string [s] matching
    a regular expression [re] can be "pumped" by repeating some middle
    section of [s] an arbitrary number of times to produce a new
    string also matching [re].

    To begin, we need to define "sufficiently long."  Since we are
    working in a constructive logic, we actually need to be able to
    calculate, for each regular expression [re], the minimum length
    for strings [s] to guarantee "pumpability." *)

Module Pumping.

Fixpoint pumping_constant {T} (re : @reg_exp T) : nat :=
  match re with
  | EmptySet => 0
  | EmptyStr => 1
  | Char _ => 2
  | App re1 re2 =>
      pumping_constant re1 + pumping_constant re2
  | Union re1 re2 =>
      pumping_constant re1 + pumping_constant re2
  | Star _ => 1
  end.

(** Next, it is useful to define an auxiliary function that repeats a
    string (appends it to itself) some number of times. *)

Fixpoint napp {T} (n : nat) (l : list T) : list T :=
  match n with
  | 0 => []
  | S n' => l ++ napp n' l
  end.

Lemma napp_plus: forall T (n m : nat) (l : list T),
  napp (n + m) l = napp n l ++ napp m l.
Proof.
  intros T n m l.
  induction n as [|n IHn].
  - reflexivity.
  - simpl. rewrite IHn, app_assoc. reflexivity.
Qed.

(** Now, the pumping lemma itself says that, if [s =~ re] and if the
    length of [s] is at least the pumping constant of [re], then [s]
    can be split into three substrings [s1 ++ s2 ++ s3] in such a way
    that [s2] can be repeated any number of times and the result, when
    combined with [s1] and [s3] will still match [re].  Since [s2] is
    also guaranteed not to be the empty string, this gives us
    a (constructive!) way to generate strings matching [re] that are
    as long as we like. *)

Lemma pumping : forall T (re : @reg_exp T) s,
  s =~ re ->
  pumping_constant re <= length s ->
  exists s1 s2 s3,
    s = s1 ++ s2 ++ s3 /\
    s2 <> [] /\
    forall m, s1 ++ napp m s2 ++ s3 =~ re.

(** To streamline the proof (which you are to fill in), the [omega]
    tactic, which is enabled by the following [Require], is helpful in
    several places for automatically completing tedious low-level
    arguments involving equalities or inequalities over natural
    numbers.  We'll return to [omega] in a later chapter, but feel
    free to experiment with it now if you like.  The first case of the
    induction gives an example of how it is used. *)

Import Coq.omega.Omega.

Proof.
  intros T re s Hmatch.
  induction Hmatch
    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2
       | s1 re1 re2 Hmatch IH | re1 s2 re2 Hmatch IH
       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].
  - (* MEmpty *)
    simpl. omega.
  (* FILL IN HERE *) Admitted.

End Pumping.
(** [] *)

(* ################################################################# *)
(** * Case Study: Improving Reflection *)

(** We've seen in the [Logic] chapter that we often need to
    relate boolean computations to statements in [Prop].  But
    performing this conversion as we did it there can result in
    tedious proof scripts.  Consider the proof of the following
    theorem: *)

Theorem filter_not_empty_In : forall n l,
  filter (beq_nat n) l <> [] ->
  In n l.
Proof.
  intros n l. induction l as [|m l' IHl'].
  - (* l = [] *)
    simpl. intros H. apply H. reflexivity.
  - (* l = m :: l' *)
    simpl. destruct (beq_nat n m) eqn:H.
    + (* beq_nat n m = true *)
      intros _. rewrite beq_nat_true_iff in H. rewrite H.
      left. reflexivity.
    + (* beq_nat n m = false *)
      intros H'. right. apply IHl'. apply H'.
Qed.

(** In the first branch after [destruct], we explicitly apply
    the [beq_nat_true_iff] lemma to the equation generated by
    destructing [beq_nat n m], to convert the assumption [beq_nat n m
    = true] into the assumption [n = m]; then we had to [rewrite]
    using this assumption to complete the case. *)

(** We can streamline this by defining an inductive proposition that
    yields a better case-analysis principle for [beq_nat n m].
    Instead of generating an equation such as [beq_nat n m = true],
    which is generally not directly useful, this principle gives us
    right away the assumption we really need: [n = m]. *)

Inductive reflect (P : Prop) : bool -> Prop :=
| ReflectT : P -> reflect P true
| ReflectF : ~ P -> reflect P false.

(** The [reflect] property takes two arguments: a proposition
    [P] and a boolean [b].  Intuitively, it states that the property
    [P] is _reflected_ in (i.e., equivalent to) the boolean [b]: that
    is, [P] holds if and only if [b = true].  To see this, notice
    that, by definition, the only way we can produce evidence that
    [reflect P true] holds is by showing that [P] is true and using
    the [ReflectT] constructor.  If we invert this statement, this
    means that it should be possible to extract evidence for [P] from
    a proof of [reflect P true].  Conversely, the only way to show
    [reflect P false] is by combining evidence for [~ P] with the
    [ReflectF] constructor.

    It is easy to formalize this intuition and show that the two
    statements are indeed equivalent: *)

Theorem iff_reflect : forall P b, (P <-> b = true) -> reflect P b.
Proof.
  (* WORKED IN CLASS *)
  intros P b H. destruct b.
  - apply ReflectT. rewrite H. reflexivity.
  - apply ReflectF. rewrite H. intros H'. inversion H'.
Qed.

(** **** Exercise: 2 stars, recommended (reflect_iff)  *)
Theorem reflect_iff : forall P b, reflect P b -> (P <-> b = true).
Proof.
(* Fill IN HERE *) Admitted.
(** [] *)

(** The advantage of [reflect] over the normal "if and only if"
    connective is that, by destructing a hypothesis or lemma of the
    form [reflect P b], we can perform case analysis on [b] while at
    the same time generating appropriate hypothesis in the two
    branches ([P] in the first subgoal and [~ P] in the second). *)

Lemma beq_natP : forall n m, reflect (n = m) (beq_nat n m).
Proof.
  intros n m. apply iff_reflect. rewrite beq_nat_true_iff. reflexivity.
Qed.

(** The new proof of [filter_not_empty_In] now goes as follows.
    Notice how the calls to [destruct] and [apply] are combined into a
    single call to [destruct]. *)

(** (To see this clearly, look at the two proofs of
    [filter_not_empty_In] with Coq and observe the differences in
    proof state at the beginning of the first case of the
    [destruct].) *)

Theorem filter_not_empty_In' : forall n l,
  filter (beq_nat n) l <> [] ->
  In n l.
Proof.
  intros n l. induction l as [|m l' IHl'].
  - (* l = [] *)
    simpl. intros H. apply H. reflexivity.
  - (* l = m :: l' *)
    simpl. destruct (beq_natP n m) as [H | H].
    + (* n = m *)
      intros _. rewrite H. left. reflexivity.
    + (* n <> m *)
      intros H'. right. apply IHl'. apply H'.
Qed.

(** **** Exercise: 3 stars, recommended (beq_natP_practice)  *)
(** Use [beq_natP] as above to prove the following: *)

Fixpoint count n l :=
  match l with
  | [] => 0
  | m :: l' => (if beq_nat n m then 1 else 0) + count n l'
  end.

Theorem beq_natP_practice : forall n l,
  count n l = 0 -> ~(In n l).
Proof.
(* Fill IN HERE *) Admitted.
(** [] *)

(** In this small example, this technique gives us only a rather small
    gain in convenience for the proofs we've seen; however, using
    [reflect] consistently often leads to noticeably shorter and
    clearer scripts as proofs get larger.  We'll see many more
    examples in later chapters and in _Programming Language
    Foundations_.

    The use of the [reflect] property was popularized by _SSReflect_,
    a Coq library that has been used to formalize important results in
    mathematics, including as the 4-color theorem and the
    Feit-Thompson theorem.  The name SSReflect stands for _small-scale
    reflection_, i.e., the pervasive use of reflection to simplify
    small proof steps with boolean computations. *)

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

(** **** Exercise: 3 stars, recommended (nostutter_defn)  *)
(** Formulating inductive definitions of properties is an important
    skill you'll need in this course.  Try to solve this exercise
    without any help at all.

    We say that a list "stutters" if it repeats the same element
    consecutively.  (This is different from the [NoDup] property in
    the exercise above: the sequence [1;4;1] repeats but does not
    stutter.)  The property "[nostutter mylist]" means that
    [mylist] does not stutter.  Formulate an inductive definition for
    [nostutter]. *)

Inductive nostutter {X:Type} : list X -> Prop :=
 (* FILL IN HERE *)
.
(** Make sure each of these tests succeeds, but feel free to change
    the suggested proof (in comments) if the given one doesn't work
    for you.  Your definition might be different from ours and still
    be correct, in which case the examples might need a different
    proof.  (You'll notice that the suggested proofs use a number of
    tactics we haven't talked about, to make them more robust to
    different possible ways of defining [nostutter].  You can probably
    just uncomment and use them as-is, but you can also prove each
    example with more basic tactics.)  *)

Example test_nostutter_1: nostutter [3;1;4;1;5;6].
(* FILL IN HERE *) Admitted.
(*
  Proof. repeat constructor; apply beq_nat_false_iff; auto.
  Qed.
*)

Example test_nostutter_2:  nostutter (@nil nat).
(* FILL IN HERE *) Admitted.
(*
  Proof. repeat constructor; apply beq_nat_false_iff; auto.
  Qed.
*)

Example test_nostutter_3:  nostutter [5].
(* FILL IN HERE *) Admitted.
(*
  Proof. repeat constructor; apply beq_nat_false; auto. Qed.
*)

Example test_nostutter_4:      not (nostutter [3;1;1;4]).
(* FILL IN HERE *) Admitted.
(*
  Proof. intro.
  repeat match goal with
    h: nostutter _ |- _ => inversion h; clear h; subst
  end.
  contradiction H1; auto. Qed.
*)
(** [] *)

(** **** Exercise: 4 stars, advanced (filter_challenge)  *)
(** Let's prove that our definition of [filter] from the [Poly]
    chapter matches an abstract specification.  Here is the
    specification, written out informally in English:

    A list [l] is an "in-order merge" of [l1] and [l2] if it contains
    all the same elements as [l1] and [l2], in the same order as [l1]
    and [l2], but possibly interleaved.  For example,

    [1;4;6;2;3]

    is an in-order merge of

    [1;6;2]

    and

    [4;3].

    Now, suppose we have a set [X], a function [test: X->bool], and a
    list [l] of type [list X].  Suppose further that [l] is an
    in-order merge of two lists, [l1] and [l2], such that every item
    in [l1] satisfies [test] and no item in [l2] satisfies test.  Then
    [filter test l = l1].

    Translate this specification into a Coq theorem and prove
    it.  (You'll need to begin by defining what it means for one list
    to be a merge of two others.  Do this with an inductive relation,
    not a [Fixpoint].)  *)

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

(** **** Exercise: 5 stars, advanced, optional (filter_challenge_2)  *)
(** A different way to characterize the behavior of [filter] goes like
    this: Among all subsequences of [l] with the property that [test]
    evaluates to [true] on all their members, [filter test l] is the
    longest.  Formalize this claim and prove it. *)

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

(** **** Exercise: 4 stars, optional (palindromes)  *)
(** A palindrome is a sequence that reads the same backwards as
    forwards.

    - Define an inductive proposition [pal] on [list X] that
      captures what it means to be a palindrome. (Hint: You'll need
      three cases.  Your definition should be based on the structure
      of the list; just having a single constructor like

        c : forall l, l = rev l -> pal l

      may seem obvious, but will not work very well.)

    - Prove ([pal_app_rev]) that

       forall l, pal (l ++ rev l).

    - Prove ([pal_rev] that)

       forall l, pal l -> l = rev l.
*)

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

(** **** Exercise: 5 stars, optional (palindrome_converse)  *)
(** Again, the converse direction is significantly more difficult, due
    to the lack of evidence.  Using your definition of [pal] from the
    previous exercise, prove that

     forall l, l = rev l -> pal l.
*)

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

(** **** Exercise: 4 stars, advanced, optional (NoDup)  *)
(** Recall the definition of the [In] property from the [Logic]
    chapter, which asserts that a value [x] appears at least once in a
    list [l]: *)

(* Fixpoint In (A : Type) (x : A) (l : list A) : Prop :=
   match l with
   | [] => False
   | x' :: l' => x' = x \/ In A x l'
   end *)

(** Your first task is to use [In] to define a proposition [disjoint X
    l1 l2], which should be provable exactly when [l1] and [l2] are
    lists (with elements of type X) that have no elements in
    common. *)

(* FILL IN HERE *)

(** Next, use [In] to define an inductive proposition [NoDup X
    l], which should be provable exactly when [l] is a list (with
    elements of type [X]) where every member is different from every
    other.  For example, [NoDup nat [1;2;3;4]] and [NoDup
    bool []] should be provable, while [NoDup nat [1;2;1]] and
    [NoDup bool [true;true]] should not be.  *)

(* FILL IN HERE *)

(** Finally, state and prove one or more interesting theorems relating
    [disjoint], [NoDup] and [++] (list append).  *)

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

(** **** Exercise: 4 stars, advanced, optional (pigeonhole_principle)  *)
(** The _pigeonhole principle_ states a basic fact about counting: if
    we distribute more than [n] items into [n] pigeonholes, some
    pigeonhole must contain at least two items.  As often happens, this
    apparently trivial fact about numbers requires non-trivial
    machinery to prove, but we now have enough... *)

(** First prove an easy useful lemma. *)

Lemma in_split : forall (X:Type) (x:X) (l:list X),
  In x l ->
  exists l1 l2, l = l1 ++ x :: l2.
Proof.
  (* FILL IN HERE *) Admitted.

(** Now define a property [repeats] such that [repeats X l] asserts
    that [l] contains at least one repeated element (of type [X]).  *)

Inductive repeats {X:Type} : list X -> Prop :=
  (* FILL IN HERE *)
.

(** Now, here's a way to formalize the pigeonhole principle.  Suppose
    list [l2] represents a list of pigeonhole labels, and list [l1]
    represents the labels assigned to a list of items.  If there are
    more items than labels, at least two items must have the same
    label -- i.e., list [l1] must contain repeats.

    This proof is much easier if you use the [excluded_middle]
    hypothesis to show that [In] is decidable, i.e., [forall x l, (In x
    l) \/ ~ (In x l)].  However, it is also possible to make the proof
    go through _without_ assuming that [In] is decidable; if you
    manage to do this, you will not need the [excluded_middle]
    hypothesis. *)

Theorem pigeonhole_principle: forall (X:Type) (l1  l2:list X),
   excluded_middle ->
   (forall x, In x l1 -> In x l2) ->
   length l2 < length l1 ->
   repeats l1.
Proof.
   intros X l1. induction l1 as [|x l1' IHl1'].
  (* FILL IN HERE *) Admitted.
(** [] *)

(** $Date: 2017-11-15 14:12:04 -0500 (Wed, 15 Nov 2017) $ *)


Require Import Essentials.Notations.
Require Import Essentials.Types.
Require Import Essentials.Facts_Tactics.
Require Import Category.Main.
Require Import Ext_Cons.Prod_Cat.Prod_Cat Ext_Cons.Prod_Cat.Operations.
Require Import Functor.Main.

Local Open Scope morphism_scope.

(**
Given two objects a and b, their product a×b is an object such that there are two projections from it to a and b:

#

                    π₁        π₂
                a <—–——– a×b ———–—> b

#
such that for any object z with two projections to a and b, there is a unique arrow h that makes the following diagram commute:

#

                    π₁        π₂
                a <—–——–– a×b –———–—> b
                 ↖         ↑        ↗
                  \        |       /
                   \       |      /
                    \      |∃!h  /
                     \     |    /
                      \    |   /
                       \   |  /
                           z

#
*)
Record Product {C : Category} (c d : C) : Type :=
{
  product : C;

  Pi_1 : product –≻ c;

  Pi_2 : product –≻ d;

  Prod_morph_ex : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d), p' –≻ product;

  Prod_morph_com_1 : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d),
      (Pi_1 ∘ (Prod_morph_ex p' r1 r2))%morphism = r1;

  Prod_morph_com_2 : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d),
      (Pi_2 ∘ (Prod_morph_ex p' r1 r2))%morphism = r2;

  Prod_morph_unique : ∀ (p' : Obj) (r1 : p' –≻ c) (r2 : p' –≻ d) (f g : p' –≻ product),
      Pi_1 ∘ f = r1
      → Pi_2 ∘ f = r2
      → Pi_1 ∘ g = r1
      → Pi_2 ∘ g = r2
      → f = g
}.

Arguments Product _ _ _, {_} _ _.

Arguments Pi_1 {_ _ _ _}, {_ _ _} _.
Arguments Pi_2 {_ _ _ _}, {_ _ _} _.
Arguments Prod_morph_ex {_ _ _} _ _ _ _.
Arguments Prod_morph_com_1 {_ _ _} _ _ _ _.
Arguments Prod_morph_com_2 {_ _ _} _ _ _ _.
Arguments Prod_morph_unique {_ _ _} _ _ _ _ _ _ _ _ _ _.

Coercion product : Product >-> Obj.

(** for any pair of objects, their product is unique up to isomorphism. *)
Theorem Product_iso {C : Category} (c d : Obj) (P : Product c d) (P' : Product c d) : (P ≃ P')%isomorphism.
Proof.
  eapply (Build_Isomorphism _ _ _ (Prod_morph_ex P' P Pi_1 Pi_2) (Prod_morph_ex P P' Pi_1 Pi_2));
  eapply Prod_morph_unique; eauto;
  rewrite <- assoc;
  repeat (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); auto.
Qed.

Definition Has_Products (C : Category) : Type := ∀ a b, Product a b.

Existing Class Has_Products.

(**
The product functor maps each pair of objects (an object of the product category C×C) to their product in C.
*)
Program Definition Prod_Func (C : Category) {HP : Has_Products C} : ((C × C) –≻ C)%functor :=
{|
  FO := fun x => HP (fst x) (snd x);
  FA := fun a b f => Prod_morph_ex _ _ ((fst f) ∘ Pi_1) ((snd f) ∘ Pi_2)
|}.

Next Obligation. (* F_id *)
Proof.
  eapply Prod_morph_unique; try reflexivity; [rewrite Prod_morph_com_1|rewrite Prod_morph_com_2]; auto.
Qed.

Next Obligation. (* F_compose *)
Proof.
  eapply Prod_morph_unique; try ((rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); reflexivity);
  repeat rewrite <- assoc; (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2);
  rewrite assoc; (rewrite Prod_morph_com_1 || rewrite Prod_morph_com_2); auto.
Qed.

Arguments Prod_Func _ _, _ {_}.

(** Sum is the dual of product *)
Definition Sum (C : Category) := @Product (C^op).

Arguments Sum _ _ _, {_} _ _.

Definition Has_Sums (C : Category) : Type :=  ∀ (a b : C), Sum a b.

Existing Class Has_Sums.

(**
The sum functor maps each pair of objects (an object of the product category C×C) to their sum in C.
*)
Definition Sum_Func {C : Category} {HS : Has_Sums C} : ((C × C) –≻ C)%functor := (Prod_Func (C^op) HS)^op.

Arguments Sum_Func _ _, _ {_}.


(** 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 (lf2 : natural) (z : natural) (x : natural) : natural :=
  plus lf2 (mult x z).


Require Import List Arith.
Import ListNotations.

Inductive Subseq : list nat -> list nat -> Prop :=
| Subseq_nil : Subseq [] []
| Subseq_take : forall a xs ys, Subseq xs ys -> Subseq (a :: xs) (a :: ys)
| Subseq_drop : forall a xs ys, Subseq xs ys -> Subseq xs (a :: ys).

Fixpoint subseq_match (xs ys : list nat) : bool :=
  match xs with
  | [] => true
  | x :: xs' =>
    (fix go (us : list nat) :=
      match us with
      | [] => false
      | u :: us' =>
          if x =? u
          then subseq_match xs' us'
          else go us'
      end) ys
  end.

Theorem subseq_match_take xs ys a: subseq_match xs ys = subseq_match (a :: xs) (a :: ys).
Proof.
  simpl.
  rewrite (Nat.eqb_refl).
  easy.
Qed.

Theorem subseq_match_drop xs ys a: subseq_match xs ys = true -> subseq_match xs (a :: ys) = true.
Proof.
  intros.
  revert dependent ys.
  revert dependent a.
  induction xs; [easy| ]; intros.
  simpl in *.
  destruct (Nat.eqb_spec a a0); subst.
  destruct ys; [easy | ].
  destruct (Nat.eqb_spec a0 n); subst.
  apply IHxs.
  exact H.
  apply IHxs.
  destruct ys.
  easy.

Qed.

Theorem subseq_match_correct : forall (xs ys : list nat),
  subseq_match xs ys = true <-> Subseq xs ys.
Proof.
  intros.
  generalize dependent xs.
  induction ys; intros; split; intros.
    - destruct xs.
      + constructor.
      + simpl in H.
        discriminate.
    - inversion H. simpl. easy.
    - destruct xs.
      + constructor.
        apply IHys.
        simpl.
        easy.
      + simpl in H.
        destruct (Nat.eqb_spec n a); subst.
        * constructor.
          apply IHys.
          exact H.
        * constructor.
          apply IHys.
          exact H.
    - destruct xs.
      + simpl. easy.
      + inversion H; subst.
        simpl.
        rewrite (Nat.eqb_refl a).
        apply IHys.
        exact H1.
        apply IHys in H2.
        simpl.
        destruct (Nat.eqb_spec n a); subst.


(*
Серия семинаров по Coq.

Домашние задания помечены комментарием с заголовком HW
и являются одним из двух:
- теоремы с доказательством admit.
- определения без тела.
Смыслом задания является приведение содержательного доказательства/определения.
 *)

(*
Иерархия типов данных в Coq такова:
Set - всякие данные (те самые сеты)
Prop - утверждения пропозициональной логики.
Type - тип для Set и Prop
Вообще, бывают Type(i) - всевозможных рангов до бесконечности, и работает
следующее:
Set : Type(1)
Prop : Type(1)
Type(i) : Type(i + 1)

TO READ: Reference manual, 4.1.1

В Coq уже встроено большое количество стандартных структур данных,
таких как bool, nat, пары и +-типы. Про них уже доказано куча классных теорем в библиотеке.
Но в образовательных целях мы переопределим их заново, а так же определим классные множества,
про которые рассказывал Миша. *)

(* Для начала нам понадобятся собственные пропозициональные True и False *)
Inductive True' : Prop := I : True'.
Inductive False' : Prop :=.

Notation "~ A" := (A -> False') : My_scope.

Open Scope My_scope.

(* На самом деле, равенство в Coq реализовано именно так, Нет встроенного понятия равенства.
Есть только обычный дататайп и немного сахара.
Отличие от нашего Id, как и раньше, будет заключаться в домене - не Set, а Prop.

Inductive eq (A:Type) (x:A) : A -> Prop :=
    eq_refl : x = x :>A

where "x = y :> A" := (@eq A x y) : type_scope.

Notation "x = y" := (x = y :>_) : type_scope.
*)

Inductive Id {A : Type} (a : A) : A -> Type :=
  id : Id a a.

Infix "==" := Id (at level 70) : My_scope.
Notation "x /= y" := (~ (x == y)) (at level 70) : My_scope.

(* Сделаем собственные пропозициональные Or и And *)

Inductive And (A B : Prop) : Prop :=
  conj' : A -> B -> And A B.

Implicit Arguments conj'.

Inductive Or (A B : Prop) : Prop :=
  inl' : A -> Or A B
| inr' : B -> Or A B.

Implicit Arguments inl'.
Implicit Arguments inr'.

Infix "/.\" := And (at level 80, right associativity) : My_scope.
Infix "\./" := Or (at level 85, right associativity) : My_scope.

(* И теперь Bool *)
Inductive Bool : Set :=
| true' : Bool
| false' : Bool.

(* Свой bool у нас есть, смоделируем собственную конструкцию if *)
Definition if' (C : Bool -> Set) (b : Bool) (c1 : C true') (c2 : C false') : C b :=
  match b with
    true' => c1
  | false' => c2
  end.

Section Elimination_proof.
  Variable C : Bool -> Set.
  Variable b : Bool.
  Variable c1 : C true'.
  Variable c2 : C false'.

  Theorem eliminate_if' : (if' C true' c1 c2) == c1 /.\ (if' C false' c1 c2) == c2.
  Proof.
    simpl.
    exact (conj' (id c1) (id c2)).
  Qed.
End Elimination_proof.

Definition Is_true (a : Bool) := if a then True' else False'.

Definition or' (a b : Bool) : Bool :=
  match a with
    true' => true'
  | false' => b
  end.

Definition and' (a b : Bool) : Bool :=
  match a with
    true' => b
  | false' => false'
  end.

Infix "||" := or' : My_scope.
Infix "&&" := and' : My_scope.

(* Первая содержательная теорема - коммутативность || *)
Theorem or_commutes : forall a b : Bool, a || b == b || a.
Proof.
  intros a b.
  case a, b.
  simpl.
  exact (id true').
  simpl.
  exact (id true').
  simpl.
  exact (id true').
  simpl.
  exact (id false').
Qed.
(* То же можно доказать про * *)

(* Empty set *)
(* Это, по сути, то же самое, что встроенный False, только не из Prop, а из Set. -- необитаемый тип *)
Inductive Empty : Set :=.

(* Числа Пеано *)
Inductive Nat : Set :=
| zero : Nat
| succ : Nat -> Nat.

Fixpoint natrec
         (C : Nat -> Set)
         (d : C zero)
         (e : forall (x:Nat) (y:C x), C (succ x)) (n : Nat)
  : C n :=
  match n with
    zero => d
  | succ n' => e n' (natrec C d e n')
  end.

Definition plus' (n m : Nat) : Nat :=
  natrec (fun _ => Nat) n (fun _ y => succ y) m.

Definition mul' (n m : Nat) : Nat :=
  natrec (fun _ => Nat) zero (fun _ y => plus' y n) m.

Infix "+" := plus' : My_scope.
Infix "*" := mul' : My_scope.

(* Докажем пару классных теорем про чиселки *)
Theorem zero_neutral_right : forall n : Nat, n + zero == n.
Proof.
  intros n.
  unfold plus'.
  simpl.
  exact (id n).
Qed.

(* Это было просто, видимо, тут будет так же просто, верно? А вот не совсем! *)
Theorem zero_neutral_left : forall n : Nat, zero + n == n.
Proof.
  intros n.
  unfold plus'.
  elim n.
  (* base *)
  simpl.
  exact (id zero).
  (* shift *)
  intros n0.
  intros ind_hypo.
  simpl.
  rewrite ind_hypo.
  exact (id (succ n0)).
Qed.

(* Нам пришлось воспользоваться индукцией (правило elim), чтобы доказать это утверждение. Это из-за устройства функции natrec: она матчится по второму аргументу, поэтому, если второй аргумент равен 0, то ее можно легко упростить. *)

(* Теперь теоремка повеселее. *)
Theorem plus'_commutes : forall n m, n + m == m + n.
Proof.
  intros n m.
  elim n.
  (* base *)
  simpl.
  exact (zero_neutral_left m).
  (* shift *)
  unfold plus'.
  intros n0.
  intros ind_hyp_n.
  simpl.
  rewrite <- ind_hyp_n.
  elim m.
  (* base *)
  simpl.
  exact (id (succ n0)).
  (* shift *)
  intros n1.
  intros ind_hyp_m.
  simpl.
  rewrite ind_hyp_m.
  exact (id (succ (succ (n0 + n1)))).
Qed.

(* HW: Ассоциативность сложения *)
Theorem plus'_associates : forall a b c, (a + b) + c == a + (b + c).
Proof.
  admit.
Qed.

(* HW: Коммутативность умножения *)
Theorem mul'_commutes : forall a b, a * b == b * a.
Proof.
  admit.
Qed.

(* HW: Дистрибутивность умножения по отношению к сложению *)
Theorem mul'_distributes_over_plus' : forall a b c, a * (b + c) == a * b + a * c.
Proof.
  admit.
Qed.

(* Простые пары *)
Inductive andS (A B : Set) : Set :=
  conjS : A -> B -> andS A B.

Definition fst (A B : Set) (p : andS A B) :=
  match p with conjS a _ => a end.

Definition snd (A B : Set) (p : andS A B) :=
  match p with conjS _ b => b end.

(* П-типы *)
Inductive Pi (A : Set) (B : A -> Set) : Set :=
  lambda : (forall x : A, B x) -> Pi A B.

Definition apply' (A : Set) (B : A -> Set) (g : Pi A B) (a : A) : B a :=
  match g with
    lambda f => f a
  end.

(* Мы умеем делать синтаксический сахар для наших конструкций *)

Notation "A ~> B" := (Pi A (fun _ => B)) (at level 90, right associativity) : My_scope.
Notation "~' A" := (A ~> Empty) (at level 75, right associativity) : My_scope.

Definition lambda' (A:Set) (B:Set) (f: forall a: A, B) : A ~> B :=
  lambda A (fun _ => B) f.

Definition apply'' (A:Set) (B:Set) (g: A ~> B) (a : A) : B :=
  apply' A (fun _ => B) g a.

(* Теперь докажем, что тип A -> ~~A обитаем! *)
Theorem remove_double_not_inhabitable : forall A : Set, A ~> ~'~'A.
Proof.
  intros A.
  exact (lambda' A (~'~'A)
                 (fun x => lambda' (~'A) Empty
                                  (fun y => apply'' A Empty y x))).
Qed.
(* Да, мы просто переписали Мишину конструкцию и все получилось! *)

(* + - тип *)
Inductive orS (A B : Set) : Set :=
| inlS : A -> orS A B
| inrS : B -> orS A B.

Definition when
           (A B : Set)
           (C : orS A B -> Set)
           (p : orS A B)
           (f : forall x:A, C (inlS A B x))
           (g : forall y:B, C (inrS A B y)) : C p
  := match p with
       inlS a => f a
     | inrS b => g b
     end.

(* Sigma - тип *)
(*
На самом деле, в Coq есть сигма-тип, но на Prop-ах. Только он не встроен в язык,
как forall, а определяется через него следующим образом:

Inductive ex (A:Type) (P:A -> Prop) : Prop :=
  ex_intro : forall x:A, P x -> ex (A:=A) P.

Notation "'exists' x .. y , p" := (ex (fun x => .. (ex (fun y => p)) ..))
  (at level 200, x binder, right associativity,
   format "'[' 'exists'  '/  ' x  ..  y ,  '/  ' p ']'")
  : type_scope.

Мы сделаем сейчас то же самое, только Type и Prop поменяем на Set - это будет сигма-типа
*)

Inductive Sigma (A : Set) (B : A -> Set) : Set :=
  pair : forall a : A, forall b : B a, Sigma A B.

Definition split'
           (A : Set)
           (B : A -> Set)
           (C : Sigma A B -> Set)
           (d : forall a:A, forall b:B a, C (pair A B a b))
           (p : Sigma A B) : C p
  := match p with
       pair a b => d a b
     end.

Definition fst' (A : Set) (B : A -> Set) (p : Sigma A B) : A :=
  split' A B (fun _ => A) (fun x _ => x) p.

Definition snd' (A : Set) (B : A -> Set) (p : Sigma A B) : B (fst' A B p) :=
  split' A B (fun x => B (fst' A B x)) (fun _ y => y) p.

(*
Мы знаем о таком утверждении на кванторах: forall x, ~(P x) -> ~(exists x, P x)
Докажем такое утверждение для П и ∑ типов: если тип П(A, [x] ¬B(x)) обитаем, то каждому его
элементу можно привести в соответствие элемент типа ¬∑(A, B).
*)

(* HW: Правило замены кванторов для П и ∑-типов *)
Theorem forall_exists :
  forall (A:Set) (B : A -> Set),
    (Pi A (fun x => ~'(B x))) ~> ~'(Sigma A B).
Proof.
  admit.
Qed.

(* Списки *)
(*
Списки есть в стандартной библиотеке Coq. Списки имеют 2 конструктора: nil и cons.
Однако, мы сделаем свои
 *)
Inductive List (A : Set) : Set :=
| nil' : List A
| cons' : A -> List A -> List A.

(* Дефолтный Head в Coq принимает аргумент default на случай пустого списка. *)
Definition head (A : Set) (def : A) (l : List A) : A :=
  match l with
    nil' => def
  | cons' x xs => x
  end.

(* Можно также написать head, который возвращает Maybe A *)
Inductive Maybe (A : Set) : Set :=
  Nothing : Maybe A
| Just : A -> Maybe A.

Definition head' (A : Set) (l : List A) : Maybe A :=
  match l with
    nil' => Nothing A
  | cons' x xs => Just A x
  end.

(* Однако только в Coq (и подобных ему языках) можно сделать никогда не падающий head,
принимающий доказательство непустоты списка *)
(* HW: Написать всегда работающий head со следующей сигнатурой *)
Definition head'' (A : Set) (l : List A) (pr : l /= nil' A) : A.
Proof.
  admit.
Qed.

Definition tail (A : Set) (l : List A) : List A :=
  match l with
    nil' => nil' A
  | cons' x xs => xs
  end.

Fixpoint foldr
         (A : Set)
         (C : List A -> Set)
         (c : C (nil' A))
         (e : forall (x:A) (y:List A) (z:C y), C (cons' A x y))
         (l : List A) : C l
  := match l with
       nil' => c
     | cons' a l' => e a l' (foldr A C c e l')
     end.

(*
Наконец пошла нормальная теория.
Сейчас мы введем множество абстрактных математических понятий насчет отношений.
Из этих очень абстрактных понятий мы сможем вывести массу полезнейших утверждений.
*)

(* Введем понятие *отношения* над множествами *)
Section Relation_definitions.
  Variable A : Type.
  Definition Relation (S : Type) := S -> S -> Prop.
  Variable R : Relation A.

  (* Определим основные свойства отношений, которые нам нужны *)
  Section General_Properties_of_Relations.
    Definition reflexive : Prop := forall x:A, R x x.
    Definition transitive : Prop := forall x y z:A, R x y -> R y z -> R x z.
    Definition symmetric : Prop := forall x y:A, R x y -> R y x.
    Definition antisymmetric : Prop := forall x y:A, R x y -> R y x -> x == y.

    (* Определение отношения эквивалентности *)
    Definition equiv := reflexive /.\ transitive /.\ symmetric.
  End General_Properties_of_Relations.

  Section Meta_relations.
    (* Определение отношения "меньше" (включения) на отношениях *)
    Definition inclusion (R1 R2: Relation A) : Prop := forall x y:A, R1 x y -> R2 x y.

    (* Равенство отношений *)
    Definition equal_rels (R1 R2: Relation A) : Prop := inclusion R1 R2 /.\ inclusion R2 R1.

  End Meta_relations.

End Relation_definitions.

(* Экстенциональность функции - очень классное свойство, которое позволяет сохранять
отношение эквивалентности между элементами при их отображении куда-то *)
Section Extensionality_definition.
  Variable A B : Type.
  Variable R1 : Relation A.
  Variable R2 : Relation B.

  Definition extensional (f:A -> B) := forall x y:A, R1 x y -> R2 (f x) (f y).

End Extensionality_definition.

(*
HW: Доказать следующую теорему:
Минимальное рефлексивное отношение
а) является отношением эквивалентности
б) таково, что для любого множества B и отношения эквивалентности на нем R2 любая функция f: A -> B экстенциональна по отношению к нашему отношению и отношению R2.
*)
Section Theorem_about_minimal_relations.
  Variable A : Type.
  Variable R : Relation A.
  Hypothesis reflR : reflexive A R.
  Hypothesis minR : forall S : Relation A, reflexive A S -> inclusion A R S.

  Theorem min_refl_rel_is_equiv :
    equiv A R /.\
    forall (B:Type) (R2:Relation B), equiv B R2 -> forall f:A -> B, extensional A B R R2 f.
  Proof.
    admit.
  Qed.
End Theorem_about_minimal_relations.

(*
HW: Доказать, что отношения равенства отношений является отношением эквивалентности
Хинт: докажите несколько лемм про более простые свойства отношений inclusion и equal_rels
*)
Theorem rels_equality_is_equivalence : forall T:Type, equiv (Relation T) (equal_rels T).
Proof.
  admit.
Qed.


Theorem plus_id_example : forall n m :nat,
                            n = m -> n + n = m + m.
Proof.
intros n m.
intros H.
rewrite -> H.
reflexivity.
Qed.

Fixpoint beq_nat (n m : nat) : bool :=
  match n with
  | O => match m with
         | O => true
         | S m' => false
         end
  | S n' => match m with
            | O => false
            | S m' => beq_nat n' m'
            end
  end.
Theorem plus_1_neq : forall n: nat,
                       beq_nat (n + 1) 0 = false.
Proof.
intros n.
destruct n.                     (* as [| n'] *)
reflexivity.
reflexivity.
Qed.

(* define my Case syntax *)

Require String. Open Scope string_scope.

Ltac move_to_top x :=
  match reverse goal with
  | H : _ |- _ => try move x after H
  end.

Tactic Notation "assert_eq" ident(x) constr(v) :=
  let H := fresh in
  assert (x = v) as H by reflexivity;
  clear H.

Tactic Notation "Case_aux" ident(x) constr(name) :=
  first [
    set (x := name); move_to_top x
  | assert_eq x name; move_to_top x
  | fail 1 "because we are working on a different case" ].

Tactic Notation "Case" constr(name) := Case_aux Case name.
Tactic Notation "SCase" constr(name) := Case_aux SCase name.
Tactic Notation "SSCase" constr(name) := Case_aux SSCase name.
Tactic Notation "SSSCase" constr(name) := Case_aux SSSCase name.
Tactic Notation "SSSSCase" constr(name) := Case_aux SSSSCase name.
Tactic Notation "SSSSSCase" constr(name) := Case_aux SSSSSCase name.
Tactic Notation "SSSSSSCase" constr(name) := Case_aux SSSSSSCase name.
Tactic Notation "SSSSSSSCase" constr(name) := Case_aux SSSSSSSCase name.

Theorem andb_true_elim1: forall b c :bool,
                           andb b c = true -> b = true.
Proof.
  intros b c H.
  destruct b.
  Case "b = true".
    reflexivity.
  Case "b = false".
    rewrite <- H.
    reflexivity.
  Qed.

Theorem plus_0_r : forall n:nat,
                     n + 0 = n.
Proof.
  intros n.
  induction n as [| n'].
  reflexivity.
  simpl.
  rewrite IHn'.
  reflexivity.
  Qed.

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

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

Theorem plus_comm : forall n m : nat,
                              n+m=m+n.
Proof.
  intros n m.
  induction n as [| n'].
  trivial.
  simpl.
  rewrite IHn'.
  apply plus_n_Sm.
  Qed.

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

(* binary *)
Inductive binary: Type :=
  | Z : binary
  | D : binary -> binary
  | E : binary -> binary.

Fixpoint incb (n:binary) : binary :=
  match n with
    | Z => E Z
    | D x => E x
    | E x => D (incb x)
  end.

Fixpoint bin_to_nat (b:binary) : nat :=
  match b with
    | Z => O
    | D x => 2 * (bin_to_nat x)
    | E x => 1+2 * (bin_to_nat x)
  end.

Theorem incb_bin_to_nat_comm:
  forall b : binary,
    bin_to_nat (incb b) = S (bin_to_nat b).
Proof.
  intros b.
  induction b.
  simpl.
  reflexivity.
  simpl.
  reflexivity.
  simpl.
  rewrite IHb.
  simpl.
  assert (H: bin_to_nat b + S (bin_to_nat b + 0) = S (bin_to_nat b + (bin_to_nat b + 0))).
  symmetry.
  apply plus_n_Sm.
  rewrite H.
  reflexivity.
Qed.

Theorem beq_nat_refl : forall n : nat,
  true = beq_nat n n.
Proof.
  intros n.
  induction n.
  simpl.
  reflexivity.
  simpl.
  apply IHn.
Qed.

Fixpoint ble_nat (n m : nat) : bool :=
  match n with
  | O => true
  | S n' =>
      match m with
      | O => false
      | S m' => ble_nat n' m'
      end
  end.


(* Copyright (c) 2022, choukh <choukyuhei@gmail.com> *)

Require Export Coq.Unicode.Utf8_core.

Fixpoint 迭代 {A : Type} (F : A → A) (a : A) (n : nat) : A :=
  match n with
  | O => a
  | S n => F (迭代 F a n)
  end.

Fixpoint f (i : nat) (n : nat) : nat :=
  match i with
  | O => S n
  | S j => 迭代 (f j) n n
  end.

Fact f_0_n : ∀ n, f 0 n = S n.
Proof. reflexivity. Qed.

Fact f_1_3 : f 1 3 = f 0 (f 0 (f 0 3)).
Proof. reflexivity. Qed.

Fact f_2_3 : f 2 3 = f 1 (f 1 (f 1 3)).
Proof. reflexivity. Qed.

Compute (f 2 10).
Compute (f 3 2).

Fact f_Sn_3 : ∀ n, f (S n) 3 = f n (f n (f n 3)).
Proof. reflexivity. Qed.

Definition g n := f n n.

Definition h n := 迭代 g n n.


Set Implicit Arguments.

Require Import
        Discrete.DiscreteType
        Finite.FinType
        Tactics.Tactics.

Import ListNotations.

Fixpoint cartesian_product {A B : Type}(xs : list A)(ys : list B) :=
  match xs with
  | [] => []
  | x :: xs' => map (fun y => (x , y)) ys ++ cartesian_product xs' ys
  end.

Lemma cartesian_product_nil {A B : Type} (xs : list A) :
  cartesian_product xs ([] : list B) = [].
Proof.
  induction xs ; crush.
Qed.

Section LEMMAS.
  Variables A B : discType.

  Lemma count_map (ys : list B) (x1 : A) y :
    count (map (fun y => (x1,y)) ys) (x1, y) = count ys y.
  Proof.
    induction ys ; crush.
    - simpl. dec ;  congruence.
  Qed.

  Lemma count_map_zero  (ys : list B) (x' x : A)  y
    : x' <> x -> count  (map (fun y => (x,y)) ys) (x', y) = 0.
  Proof.
    intros ineq. induction ys ; repeat (crush ; dec).
  Qed.

  Lemma cartesian_product_count (xs : list A) (ys : list B)(x : A)(y : B)
    : count (cartesian_product xs ys) (x,y) =  count xs x * count ys y.
  Proof.
    induction xs as [| x' xs] ; crush.
    -
      rewrite count_app. rewrite IHxs. decide (x = x') as [E | E] ; substs.
      +
        cbn. fequals*. apply count_map.
      +
        rewrite <- plus_O_n. fequals*. now apply count_map_zero.
  Qed.
End LEMMAS.

Lemma cartesian_product_enum_sound (A B : finType) (x : A * B)
  : count (cartesian_product (elem A) (elem B)) x = 1.
Proof.
  destruct x as [x y]. rewrite cartesian_product_count.
  unfold elem. now rewrite !enum_sound.
Qed.

Instance FinTypeC_Prod (A B : finType) : FinTypeC (A ** B).
Proof.
  econstructor.  apply cartesian_product_enum_sound.
Defined.

Canonical Structure FinType_Prod (A B : finType) := FinType (A ** B).

Notation "A (x) B" := (FinType_Prod A B) (at level 40, left associativity).

Lemma cardinality_cartesian_product {A B : finType}
  : Cardinality (A (x) B) = Cardinality A * Cardinality B.
Proof.
  cbn. unfold cartesian_product. unfold Cardinality.
  induction (elem A) ; crush.
  -
    cbn.
    rewrite app_length.
    rewrite IHl. f_equal. apply map_length.
Qed.


(* We can define our own boolean type *)
Inductive bool : Type :=
  | true
  | false.

Definition negb (b_0:bool) : bool :=
  match b_0 with
  | true => false
  | false => true
  end.

Definition andb (b_1:bool) (b_2:bool) : bool :=
  match b_1 with
  | true => b_2
  | false => false
  end.

Definition orb (b_1:bool) (b_2:bool) : bool :=
  match b_1 with
  | true => true
  | false => b_2
  end.

Example test_orb1: (orb true false) = true.
Proof. simpl. reflexivity. Qed.

Example test_orb2: (orb false true) = true.
Proof. simpl. reflexivity. Qed.

Example test_orb3: (orb true true) = true.
Proof. simpl. reflexivity. Qed.

Example test_orb4: (orb false false) = false.
Proof. simpl. reflexivity. Qed.

Notation "x && y" := (andb x y).
Notation "x || y" := (orb x y).

Example test_orb5: false || false || true = true.
Proof. simpl. reflexivity. Qed.

(* We can also talk about conditionals *)
Definition negb' (b:bool) : bool :=
  if b then false
  else true.

Example test_negb: (negb' false) = true.
Proof. simpl. reflexivity. Qed.

(* Excercises *)
Definition nandb (b_1:bool) (b_2:bool) : bool :=
  negb (andb b_1 b_2).

Example test_nandb1: (nandb true true) = false.
Proof. simpl. reflexivity. Qed.
Example test_nandb2: (nandb false true) = true.
Proof. simpl. reflexivity. Qed.
Example test_nandb3: (nandb true false) = true.
Proof. simpl. reflexivity. Qed.
Example test_nandb4: (nandb false false) = true.
Proof. simpl. reflexivity. Qed.


Module natlist.
Require Import Arith.
Check nat.
Check bool.

Inductive natlist: Type :=
  | nil : natlist
  | cons : nat -> natlist -> natlist.

Notation "x :: l" := (cons x l) (at level 60, right associativity).
Notation "[ ]" := nil.
Notation "[ x , .. , y ]" := (cons x .. (cons y nil) ..).
Fixpoint app (l1 l2 : natlist) : natlist :=
  match l1 with
  | nil => l2
  | h :: t => h :: (app t l2)
  end.
Notation "x ++ y" := (app x y)
                     (right associativity, at level 60).
Example test_app1: [1,2,3] ++ [4,5] = [1,2,3,4,5].
Proof. reflexivity. Qed.
Example test_app2: nil ++ [4,5] = [4,5].
Proof. reflexivity. Qed.
Example test_app3: [1,2,3] ++ nil = [1,2,3].
Proof. reflexivity. Qed.

Fixpoint length (l: natlist): nat :=
  match l with
  | nil => O
  | cons a l' => S (length l')
  end.
Example test_length1 : (length []) = 0.
Proof. reflexivity. Qed.
Example test_length2: (length [1, 2, 3]) = 3.
Proof. reflexivity. Qed.

Fixpoint rev (l: natlist) : natlist :=
  match l with
  | nil => nil
  | cons a l1' => (rev l1') ++ [a]
  end.
Example test_rev1: (rev [1, 2, 3]) = [3, 2, 1].
Proof. reflexivity. Qed.
Example test_rev2: (rev [1]) = [1].
Proof. reflexivity. Qed.

Theorem app_length : forall l1 l2 : natlist,
  length (l1 ++ l2) = (length l1) + (length l2).
Proof.
  intros l1 l2.
  induction l1 as [| n l1'].
  reflexivity.
  simpl. rewrite -> IHl1'. reflexivity. Qed.

Theorem app_ass : forall l1 l2 l3 : natlist,
  (l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3).
Proof.
  intros l1 l2 l3.
  induction l1 as [| n l1']. reflexivity.
  simpl. rewrite -> IHl1'. reflexivity. Qed.

Theorem one_length : forall n: nat,
  length [n] = 1.
Proof.
  intro n. simpl. reflexivity. Qed.
Theorem rev_length : forall l : natlist,
  length (rev l) = length l.
Proof.
  intro l.
  induction l as [| n l']. reflexivity.
  simpl. rewrite -> app_length.
  SearchRewrite(_ + _ ).
  rewrite -> Nat.add_comm.
  rewrite -> one_length. simpl.
  rewrite -> IHl'. reflexivity. Qed.

Theorem app_nil_end : forall l : natlist,
  l ++ [] = l.
Proof.
  intro l.
  induction l as [| n l']. reflexivity.
  simpl. rewrite -> IHl'. reflexivity. Qed.

Theorem rev_one : forall n : nat,
  rev [n] = [n].
 Proof. reflexivity. Qed.

Theorem rev_rev_one : forall n : nat,
  rev (rev [n]) = [n].
 Proof. reflexivity. Qed.

Theorem distr_rev : forall l1 l2 : natlist,
  rev (l1 ++ l2) = (rev l2) ++ (rev l1).
Proof.
  intros l1 l2.
  induction l1 as [| a l1']. simpl. rewrite -> app_nil_end. reflexivity.
  simpl. rewrite -> IHl1'. rewrite -> app_ass. reflexivity. Qed.

Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  intro l.
  induction l as [| n l']. reflexivity.
  simpl. rewrite <-  rev_one.
  rewrite -> distr_rev.
  rewrite -> rev_rev_one. simpl.
  rewrite -> IHl'. reflexivity. Qed.

Theorem app_ass4 : forall l1 l2 l3 l4 : natlist,
  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.
Proof.
  intros l1 l2 l3 l4.
  rewrite -> app_ass.
  rewrite -> app_ass. reflexivity. Qed.

End natlist.


Record Category :=
    {
      (* Basic elements of every category
         are obects and arrows (morphisms)
         between them. *)

      (* So we begin with Ob as set of objects *)
      Ob:     Type;

      (* Then Hom as family of sets of arrows
         parametrized by two objects –
         the begin and the end of an arrow

         For example for objects a and b
         Hom(a,b) is the set of arrows
         that starts at a and ends at b *)
      Hom:    Ob -> Ob -> Type;

      (* Also there are some propositions about
         category *)

      (* For every object a there is
         identity morphism id in Hom(a,a) *)
      Id:     forall {a},
                Hom a a;

      (* We can compose arrow.
         Suppose we have objects a, b, c.
         And two arrows f in Hom(a,b) and
         g in Hom(b,c).
         So, end of f is the start of g.
         Such arrows are composable.
         By composing them we get some
         new arrow h, h in Hom(a,c)
         *)
      Comp:   forall {a b c},
                Hom a b -> Hom b c -> Hom a c;

      (* Composing any arrow f in Hom(a,b)
         with Id  arrow we always get f arrow.

         Though, in Hom(a,a) can be
         other arrows than Id. *)
      idl:    forall a b
                     (f: Hom a b),
                Comp Id f = f;

      idr:    forall a b
                     (f: Hom a b),
                Comp f Id = f;

      (* Associativity rule for composition *)
      assoc:  forall {a b c d}
                     (f: Hom a b)
                     (g: Hom b c)
                     (h: Hom c d),
                Comp f (Comp g h) = Comp (Comp f g) h
    }.

(*
  Definition OpHom (C : Category) x y := Hom C y x.
  Variable C : Category.
  Variable x y : Ob C.
  Check OpHom C x y.
  Check Build_Category (Ob C) (OpHom C). *)


Require Import String.
Open Scope string_scope.

Inductive bird : Set :=
  | app : bird -> bird -> bird.

Module thm_9_2.

  Variable M : bird. (* ものまね鳥を示す変数 *)
  Variable E : bird. (* ものまね鳥が好きな鳥を示す変数 *)

  (*
    合成鳥の存在を示すのと同値な仮定
    (鳥の合成ルールを示す仮定)
  *)
  Hypothesis Hc : forall (A B x : bird), app A (app B x) = app (app A B) x.

  (* ものまね鳥の性質を示す仮定 *)
  Hypothesis Hm : forall (x : bird), app M x = app x x.

  (* ものまね鳥が好きな鳥を示す仮定 *)
  Hypothesis He : app M E = E. (* ← app M E が、ものまね鳥の性質により、app E E と書けることがカギ *)

  Theorem thm_9_2 :
    exists (x : bird), app x x = x.
      (*
        結論：
        ある x が存在して、 x x = x となる。
      *)
  Proof.
    exists E.
    rewrite <- He at 3.
    rewrite Hm.
    reflexivity.
  Qed.

  From mathcomp
  Require Import ssreflect.

  Theorem thm_9_2_ssr :
    exists (x : bird), app x x = x.
      (*
        結論：
        ある x が存在して、 x x = x となる。
      *)
  Proof.
    exists E.
    rewrite -{3} He. (* rewrite <- He at 3.と同じこと。 *)
    rewrite Hm.
    done.
  Qed.

End thm_9_2.


Require Import Essentials.Notations.
Require Import Essentials.Types.
Require Import Essentials.Facts_Tactics.
Require Import Category.Main.

(**
Fro categories C and C', a functor F : C -> C' consists of an arrow map from
objects of C to objects of C' and an arrow map from arrows of C to arrows of C'
such that an arrow h : a -> b is mapped to (F h) : F a -> F b.

Furthermore, we require functors to map identitiies to identities. Additionally,
the immage of the coposition of two arrows must be the same as composition of
their images.
*)
Record Functor (C C' : Category) : Type :=
{
  (** Object map *)
  FO : C → C';

  (** Arrow map *)
  FA : ∀ {a b}, (a –≻ b)%morphism → ((FO a) –≻ (FO b))%morphism;

  (** Mapping of identities *)
  F_id : ∀ c, FA (id c) = id (FO c);

  (** Functor commuting with composition *)
  F_compose : ∀ {a b c} (f : (a –≻ b)%morphism) (g : (b –≻ c)%morphism),
      (FA (g ∘ f) = (FA g) ∘ (FA f))%morphism

  (* F_id and F_compose together state the fact that functors are morphisms of
 categories (preserving the structure of categories!)*)
}.

Arguments FO {_ _} _ _.
Arguments FA {_ _} _ {_ _} _, {_ _} _ _ _ _.
Arguments F_id {_ _} _ _.
Arguments F_compose {_ _} _ {_ _ _} _ _.

Notation "C –≻ D" := (Functor C D) : functor_scope.

Bind Scope functor_scope with Functor.

Notation "F '_o'" := (FO F) : object_scope.

Notation "F '@_a'" := (@FA _ _ F) : morphism_scope.

Notation "F '_a'" := (FA F) : morphism_scope.

Hint Extern 2 => (apply F_id).

Local Open Scope morphism_scope.
Local Open Scope object_scope.

Ltac Functor_Simplify :=
  progress
    (
      repeat rewrite F_id;
      (
        repeat
          match goal with
          | [|- ?F _a ?A = id (?F _o ?x)] =>
            (rewrite <- F_id; (cbn+idtac))
          | [|- (id (?F _o ?x)) = ?F _a ?A] =>
            (rewrite <- F_id; (cbn+idtac))
          | [|- ?F _a ?A ∘ ?F _a ?B = ?F _a ?C ∘ ?F _a ?D] =>
            (repeat rewrite <- F_compose; (cbn+idtac))
          | [|- ?F _a ?A ∘ ?F _a ?B = ?F _a ?C] =>
            (rewrite <- F_compose; (cbn+idtac))
          | [|- ?F _a ?C = ?F _a ?A ∘ ?F _a ?B] =>
            (rewrite <- F_compose; (cbn+idtac))
          | [|- context [?F _a ?A ∘ ?F _a ?B]] =>
            (rewrite <- F_compose; (cbn+idtac))
          end
      )
    )
.

Hint Extern 2 => Functor_Simplify.

Section Functor_eq_simplification.

  Context {C C' : Category} (F G : (C –≻ C')%functor).

  (** Two functors are equal if their object maps and arrow maps are. *)
  Lemma Functor_eq_simplify (Oeq : F _o = G _o) :
    ((fun x y =>
        match Oeq in _ = V return ((x –≻ y) → ((V x) –≻ (V y)))%morphism with
          eq_refl => F  @_a x y
        end) = G @_a) -> F = G.
  Proof.
    destruct F; destruct G.
    basic_simpl.
    ElimEq.
    PIR.
    trivial.
  Qed.

  (** Extensionality for arrow maps of functors. *)
  Theorem FA_extensionality (Oeq : F _o = G _o) :
    (
      ∀ (a b : Obj)
        (h : (a –≻ b)%morphism),
        (
          fun x y =>
            match Oeq in _ = V return
                  ((x –≻ y) → ((V x) –≻ (V y)))%morphism
            with
              eq_refl => F  @_a x y
            end
        ) _ _ h = G _a h
    )
    →
    (
      fun x y =>
        match Oeq in _ = V return
              ((x –≻ y) → ((V x) –≻ (V y)))%morphism
        with
          eq_refl => F  @_a x y
        end
    ) = G @_a.
  Proof.
    auto.
  Qed.

  (** Fucntor extensionality: two functors are equal of their object maps are
      equal and their arrow maps are extensionally equal. *)
  Lemma Functor_extensionality (Oeq : F _o = G _o) :
    (
      ∀ (a b : Obj) (h : (a –≻ b)%morphism),
        (
          fun x y =>
            match Oeq in _ = V return
                  ((x –≻ y) → ((V x) –≻ (V y)))%morphism
            with
              eq_refl => F  @_a x y
            end
        ) _ _ h = G _a h
    ) → F = G.
  Proof.
    intros H.
    apply (Functor_eq_simplify Oeq); trivial.
    apply FA_extensionality; trivial.
  Qed.

End Functor_eq_simplification.

Hint Extern 2 => Functor_Simplify.

Ltac Func_eq_simpl :=
  match goal with
    [|- ?A = ?B :> Functor _ _] =>
    (apply (Functor_eq_simplify A B (eq_refl : A _o = B _o)%object)) +
    (cut (A _o = B _o)%object; [
       let u := fresh "H" in
       intros H;
         apply (Functor_eq_simplify A B H)
         |
    ])
  end.

Hint Extern 3 => Func_eq_simpl.

Section Functor_eq.
  Context {C C' : Category} (F G : (C –≻ C')%functor).

  Lemma Functor_eq_morph (H : F = G) :
    ∃ (H : ∀ x, F _o x = G _o x),
    ∀ x y (h : (x –≻ y)%morphism),
      match H x in _ = V return (V –≻ _)%morphism with
         eq_refl =>
         match H y in _ = V return (_ –≻ V)%morphism with
           eq_refl => F _a h
         end
       end = G _a h.
  Proof.
    exists (equal_f (f_equal FO H)).
    intros x y h.
    destruct H; trivial.
  Qed.

End Functor_eq.