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

Definition div8_spec:
 forall n,  ({q : nat & {r : nat | n = 8 * q + r /\ r < 8}}).
refine (fix
        div8 (n : nat) : {q : nat & {r : nat | n = 8 * q + r /\ r < 8}} :=
           match n return {q : nat & {r : nat | n = 8 * q + r /\ r < 8}} with
              S (S (S (S (S (S (S (S x))))))) =>
                match div8 x with existS q' (exist r (conj Heq Hlt)) => _ end
             | _ => _
           end).
exists 0; exists 0; omega.
exists 0; exists 1; omega.
exists 0; exists 2; omega.
exists 0; exists 3; omega.
exists 0; exists 4; omega.
exists 0; exists 5; omega.
exists 0; exists 6; omega.
exists 0; exists 7; omega.
exists (S q'); exists r; omega.
Qed.
(* We use a different inequality to express that the cubic root we provide is
  not an underestimation, but we will produce a more intuitive specification
  in the final function.  The specication we use here should make the proofs by
  omega easier. *)

Definition cubic_F:
 forall n,
 (forall y,
  y < n ->
   ({s : nat & {r : nat | y = (s * s) * s + r /\ r <= 3 * (s * s) + 3 * s}})) ->
  ({s : nat & {r : nat | n = (s * s) * s + r /\ r <= 3 * (s * s) + 3 * s}}).
refine (fun n cubic =>
           match div8_spec n with
             existS (S q) (exist r8 (conj Heq Hltr8)) =>
               match cubic (S q) _ with
                 existS c' (exist r (conj Heqc Hltr)) =>
                   match le_lt_dec ((12 * (c' * c') + 6 * c') + 1) (8 * r + r8)
                    with left Hle => _ | right Hlt => _ end
               end
            | existS 0 (exist 0 (conj Heq _)) => _
            | existS 0 (exist (S n') (conj Heq Hlt)) => _
           end).
exists 0; exists 0; rewrite Heq; omega.
exists 1; exists n'; rewrite Heq; omega.
omega.
exists (2 * c' + 1); exists ((8 * r + r8) - ((12 * (c' * c') + 6 * c') + 1)).
rewrite Heq.
replace
 (((2 * c' + 1) * (2 * c' + 1)) * (2 * c' + 1) +
  ((8 * r + r8) - ((12 * (c' * c') + 6 * c') + 1)))
     with
      (((8 * c') * c') * c' +
       (((12 * (c' * c') + 6 * c') + 1) +
        ((8 * r + r8) - ((12 * (c' * c') + 6 * c') + 1)))).
rewrite le_plus_minus_r.
rewrite Heqc.
split.
ring.
apply plus_le_reg_l with ((12 * (c' * c') + 6 * c') + 1).
rewrite le_plus_minus_r.
replace ((2 * c' + 1) * (2 * c' + 1)) with ((4 * (c' * c') + 4 * c') + 1).
omega.
ring.
exact Hle.
exact Hle.
ring.
exists (2 * c'); exists (8 * r + r8); split.
rewrite Heq; rewrite Heqc; ring.
replace ((2 * c') * (2 * c')) with (4 * (c' * c')).
omega.
ring.
Qed.

Definition cubic:
 forall n,
  ({c : nat &
   {r : nat | n = (c * c) * c + r /\ n < ((c + 1) * (c + 1)) * (c + 1)}}).
intros n;
 elim
  (well_founded_induction
    lt_wf
    (fun n =>
     {c : nat & {r : nat | n = (c * c) * c + r /\ r <= 3 * (c * c) + 3 * c}})
    cubic_F n).
intros c [r [Heq Hle]].
exists c; exists r; split; trivial.
replace (((c + 1) * (c + 1)) * (c + 1))
     with ((((c * c) * c + 3 * (c * c)) + 3 * c) + 1).
omega.
ring.
Qed.


Require Import Arith.
Require Import List.
Require Import Omega.

(** All elements of a list have a property. *)
Fixpoint listall A P (xs:list A) :=
  match xs with
      nil => True
    | (x::xs) => P x /\ listall _ P xs
  end.

(** All elements of a list have the same (given) value. *)
Definition allEq A xs y := listall A (fun x => x = y) xs.

(** Return the first n elements of a list. *)
Fixpoint take A n (xs : list A) :=
  match xs with
      nil => nil
    | (x::xs) =>
      match n with
          0 => nil
        | S n => x :: take _ n xs
      end
  end.

(** After conjuring up n copies of an element, taking n of them is a no-op. *)
Lemma take_repeat:
  forall A n c,
    take A n (repeat c n) = repeat c n.
Proof.
 induction n.
  simpl.
  auto.
 simpl.
 intro c.
 rewrite IHn.
 auto.
Qed.

(** Taking n elements of a concatentation, when n is less than the
    length of the first concatenand, gives just n elements of that concatenand. *)
Lemma take_app:
  forall A n (xs ys : list A),
  n <= length xs ->
  take A n (xs ++ ys) = take A n xs.
Proof.
 induction n.
  intros.
  simpl.
  destruct xs; destruct ys; auto.
 intros.
 simpl.
 destruct xs.
  simpl.
  destruct ys.
   auto.
  simpl in H.
  exfalso; omega.
 simpl.
 rewrite IHn.
  auto.
 simpl in H.
 omega.
Qed.

(** If we conjure copies of a value, all the elements of the list are equal to that value. *)
Lemma listall_repeat :
  forall A c n,
    listall A (fun x => x = c) (repeat c n).
Proof.
 induction n; simpl.
  auto.
 split; auto.
Qed.

(** Return what follows after the first n elements of a list. *)
Fixpoint drop A n (xs : list A) :=
  match n with
      0 => xs
    | S n =>
      match xs with
          nil => nil
        | (x::xs) =>
          drop _ n xs
      end
  end.

(** Dropping the first n elements of a concatenation, when n is the
    length of the first concatenand, gives just the second concatenand. *)
Lemma drop_app:
  forall A n (xs ys : list A),
    n = length xs ->
    drop A n (xs ++ ys) = ys.
Proof.
 induction n.
  intros.
  simpl.
  destruct xs; auto.
  simpl in *.
  discriminate.
 intros.
 destruct xs; simpl in *.
  discriminate.
 rewrite IHn; auto.
Qed.

Hint Rewrite take_repeat take_app drop_app app_length repeat_length : list_lemmas.


Set Implicit Arguments.

Require Import Coq.Lists.SetoidList.

Definition equiv_2 A B p1 p2 := forall (a : A) (b : B), p1 a b <-> p2 a b.

Lemma equiv_2_trans : forall A B a b c, @equiv_2 A B a b -> equiv_2 b c -> equiv_2 a c.
  unfold equiv_2; intros; split; intros.
  eapply H0; eapply H; eauto.
  eapply H; eapply H0; eauto.
Qed.

Lemma InA_eq_In_iff : forall elt (ls : list elt) (x : elt), InA eq x ls <-> List.In x ls.
  induction ls; simpl; intros.
  intuition.
  eapply InA_nil in H; eauto.
  split; intros.
  inversion H; subst.
  eauto.
  right.
  eapply IHls.
  eauto.
  destruct H.
  subst.
  econstructor 1.
  eauto.
  econstructor 2.
  eapply IHls.
  eauto.
Qed.

Lemma InA_weaken :
  forall A (P : A -> A -> Prop) (x : A) (ls : list A),
    InA P x ls ->
    forall (P' : A -> A -> Prop) x',
      (forall y, P x y -> P' x' y) ->
      InA P' x' ls.
  induction 1; simpl; intuition.
Qed.

Lemma equiv_InA : forall elt (eq1 eq2 : elt -> elt -> Prop), equiv_2 eq1 eq2 -> equiv_2 (InA eq1) (InA eq2).
  unfold equiv_2; split; intros; eapply InA_weaken; eauto; intros; eapply H; eauto.
Qed.

Lemma In_InA : forall A (x : A) ls,
  List.In x ls
  -> InA eq x ls.
  intros; eapply InA_eq_In_iff; eauto.
Qed.

Lemma InA_In : forall A (x : A) ls,
  InA eq x ls ->
  List.In x ls.
  intros; eapply InA_eq_In_iff; eauto.
Qed.

Local Hint Constructors List.NoDup NoDupA.

Lemma NoDupA_NoDup : forall A ls,
  @NoDupA A eq ls
  -> List.NoDup ls.
  induction 1; intuition auto using In_InA.
Qed.

Lemma NoDup_NoDupA : forall A ls,
  List.NoDup ls ->
  @NoDupA A eq ls.
  induction 1; intuition auto using InA_In.
Qed.


(*
Wenrui Meng finish this assignment by himself.
*)
(** * Basics: Functional Programming in Coq *)

(* This library definition is included here temporarily
   for backward compatibility with Coq 8.3.
   Please ignore. *)
Definition admit {T: Type} : T.  Admitted.

(* ###################################################################### *)
(** * Introduction *)

(** The functional programming style brings programming closer to
    mathematics: If a procedure or method has no side effects, then
    pretty much all you need to understand about it is how it maps
    inputs to outputs -- that is, you can think of its behavior as
    just computing a mathematical function.  This is one reason for
    the word "functional" in "functional programming."  This direct
    connection between programs and simple mathematical objects
    supports both sound informal reasoning and formal proofs of
    correctness.

    The other sense in which functional programming is "functional" is
    that it emphasizes the use of functions (or methods) as
    _first-class_ values -- i.e., values that can be passed as
    arguments to other functions, returned as results, stored in data
    structures, etc.  The recognition that functions can be treated as
    data in this way enables a host of useful idioms, as we will see.

    Other common features of functional languages include _algebraic
    data types_ and _pattern matching_, which make it easy to construct
    and manipulate rich data structures, and sophisticated
    _polymorphic type systems_ that support abstraction and code
    reuse.  Coq shares all of these features.
*)

(* ###################################################################### *)
(** * Enumerated Types *)

(** One unusual aspect of Coq is that its set of built-in
    features is _extremely_ small.  For example, instead of providing
    the usual palette of atomic data types (booleans, integers,
    strings, etc.), Coq offers an extremely powerful mechanism for
    defining new data types from scratch -- so powerful that all these
    familiar types arise as instances.

    Naturally, the Coq distribution comes with an extensive standard
    library providing definitions of booleans, numbers, and many
    common data structures like lists and hash tables.  But there is
    nothing magic or primitive about these library definitions: they
    are ordinary user code.

    To see how this works, let's start with a very simple example. *)

(* ###################################################################### *)
(** ** Days of the Week *)

(** The following declaration tells Coq that we are defining
    a new set of data values -- a _type_. *)

Inductive day : Type :=
  | monday : day
  | tuesday : day
  | wednesday : day
  | thursday : day
  | friday : day
  | saturday : day
  | sunday : day.

(** The type is called [day], and its members are [monday],
    [tuesday], etc.  The second through eighth lines of the definition
    can be read "[monday] is a [day], [tuesday] is a [day], etc."

    Having defined [day], we can write functions that operate on
    days. *)

Definition next_weekday (d:day) : day :=
  match d with
  | monday    => tuesday
  | tuesday   => wednesday
  | wednesday => thursday
  | thursday  => friday
  | friday    => monday
  | saturday  => monday
  | sunday    => monday
  end.

(** One thing to note is that the argument and return types of
    this function are explicitly declared.  Like most functional
    programming languages, Coq can often work out these types even if
    they are not given explicitly -- i.e., it performs some _type
    inference_ -- but we'll always include them to make reading
    easier. *)

(** Having defined a function, we should check that it works on
    some examples.  There are actually three different ways to do this
    in Coq.  First, we can use the command [Eval simpl] to evaluate a
    compound expression involving [next_weekday].  *)

Eval simpl in (next_weekday friday).
   (* ==> monday : day *)
Eval simpl in (next_weekday (next_weekday saturday)).
   (* ==> tuesday : day *)

(** If you have a computer handy, now would be an excellent
    moment to fire up the Coq interpreter under your favorite IDE --
    either CoqIde or Proof General -- and try this for yourself.  Load
    this file ([Basics.v]) from the book's accompanying Coq sources,
    find the above example, submit it to Coq, and observe the
    result. *)

(** The keyword [simpl] ("simplify") tells Coq precisely how to
    evaluate the expression we give it.  For the moment, [simpl] is
    the only one we'll need; later on we'll see some alternatives that
    are sometimes useful. *)

(** Second, we can record what we _expect_ the result to be in
    the form of a Coq example: *)

Example test_next_weekday:
  (next_weekday (next_weekday saturday)) = tuesday.

(** This declaration does two things: it makes an
    assertion (that the second weekday after [saturday] is [tuesday]),
    and it gives the assertion a name that can be used to refer to it
    later. *)
(** Having made the assertion, we can also ask Coq to verify it,
    like this: *)

Proof. simpl. reflexivity.  Qed.

(** The details are not important for now (we'll come back to
    them in a bit), but essentially this can be read as "The assertion
    we've just made can be proved by observing that both sides of the
    equality are the same after simplification." *)

(** Third, we can ask Coq to "extract," from a [Definition], a
    program in some other, more conventional, programming
    language (OCaml, Scheme, or Haskell) with a high-performance
    compiler.  This facility is very interesting, since it gives us a
    way to construct _fully certified_ programs in mainstream
    languages.  Indeed, this is one of the main uses for which Coq was
    developed.  We'll come back to this topic in later chapters.
    More information can also be found in the Coq'Art book by Bertot
    and Casteran, as well as the Coq reference manual. *)

(* ###################################################################### *)
(** ** Booleans *)

(** In a similar way, we can define the type [bool] of booleans,
    with members [true] and [false]. *)

Inductive bool : Type :=
  | true : bool
  | false : bool.

(** Although we are rolling our own booleans here for the sake
    of building up everything from scratch, Coq does, of course,
    provide a default implementation of the booleans in its standard
    library, together with a multitude of useful functions and
    lemmas.  (Take a look at [Coq.Init.Datatypes] in the Coq library
    documentation if you're interested.)  Whenever possible, we'll
    name our own definitions and theorems so that they exactly
    coincide with the ones in the standard library. *)

(** Functions over booleans can be defined in the same way as
    above: *)

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

Definition andb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => b2
  | false => false
  end.

Definition orb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => true
  | false => b2
  end.

(** The last two illustrate the syntax for multi-argument
    function definitions. *)

(** The following four "unit tests" constitute a complete
    specification -- a truth table -- for the [orb] function: *)

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

(** _A note on notation_: We use square brackets to delimit
    fragments of Coq code in comments in .v files; this convention,
    also used by the [coqdoc] documentation tool, keeps them visually
    separate from the surrounding text.  In the html version of the
    files, these pieces of text appear in a [different font]. *)

(** The values [Admitted] and [admit] can be used to fill
    a hole in an incomplete definition or proof.  We'll use them in the
    following exercises.  In general, your job in the exercises is
    to replace [admit] or [Admitted] with real definitions or proofs. *)

(** **** Exercise: 1 star (nandb) *)
(** Complete the definition of the following functions, then make
    sure that the [Example] assertions below each can be verified by
    Coq.  *)

(** This function should return [true] if either or both of
    its inputs are [false]. *)

Definition nandb (b1:bool) (b2:bool) : bool :=
  match b1 with
  | true => match b2 with
                | true => false
                | false => true
            end
  | false => true
  end.
(* FILL IN HERE *)

(** Remove "[Admitted.]" and fill in each proof with
    "[Proof. simpl. reflexivity. Qed.]" *)

Example test_nandb1:               (nandb true false) = true.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
Example test_nandb2:               (nandb false false) = true.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
Example test_nandb3:               (nandb false true) = true.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
Example test_nandb4:               (nandb true true) = false.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
(** [] *)

(** **** Exercise: 1 star (andb3) *)
Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
  (* FILL IN HERE *)
 match b1 with
     | false => false
     | true => match b2 with
                   | false => false
                   | true => match b3 with
                                 | false => false
                                 | true => true
                             end
               end
 end.

Example test_andb31:                 (andb3 true true true) = true.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
Example test_andb32:                 (andb3 false true true) = false.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
Example test_andb33:                 (andb3 true false true) = false.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
Example test_andb34:                 (andb3 true true false) = false.
(* FILL IN HERE *)
Proof. simpl. reflexivity. Qed.
(** [] *)

(* ###################################################################### *)
(** ** Function Types *)

(** The [Check] command causes Coq to print the type of an
    expression.  For example, the type of [negb true] is [bool]. *)

Check true.
(* ===> true : bool *)
Check (negb true).
(* ===> negb true : bool *)

(** Functions like [negb] itself are also data values, just like
    [true] and [false].  Their types are called _function types_, and
    they are written with arrows. *)

Check negb.
(* ===> negb : bool -> bool *)

(** The type of [negb], written [bool -> bool] and pronounced
    "[bool] arrow [bool]," can be read, "Given an input of type
    [bool], this function produces an output of type [bool]."
    Similarly, the type of [andb], written [bool -> bool -> bool], can
    be read, "Given two inputs, both of type [bool], this function
    produces an output of type [bool]." *)

(* ###################################################################### *)
(** ** Numbers *)

(** _Technical digression_: Coq provides a fairly sophisticated
    _module system_, to aid in organizing large developments.  In this
    course we won't need most of its features, but one is useful: If
    we enclose a collection of declarations between [Module X] and
    [End X] markers, then, in the remainder of the file after the
    [End], these definitions will be referred to by names like [X.foo]
    instead of just [foo].  Here, we use this feature to introduce the
    definition of the type [nat] in an inner module so that it does
    not shadow the one from the standard library. *)

Module Playground1.

(** The types we have defined so far are examples of "enumerated
    types": their definitions explicitly enumerate a finite set of
    elements.  A more interesting way of defining a type is to give a
    collection of "inductive rules" describing its elements.  For
    example, we can define the natural numbers as follows: *)

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

(** The clauses of this definition can be read:
      - [O] is a natural number (note that this is the letter "[O]," not
        the numeral "[0]").
      - [S] is a "constructor" that takes a natural number and yields
        another one -- that is, if [n] is a natural number, then [S n]
        is too.

    Let's look at this in a little more detail.

    Every inductively defined set ([weekday], [nat], [bool], etc.) is
    actually a set of _expressions_.  The definition of [nat] says how
    expressions in the set [nat] can be constructed:

    - the expression [O] belongs to the set [nat];
    - if [n] is an expression belonging to the set [nat], then [S n]
      is also an expression belonging to the set [nat]; and
    - expressions formed in these two ways are the only ones belonging
      to the set [nat]. *)

(** These three conditions are the precise force of the
    [Inductive] declaration.  They imply that the expression [O], the
    expression [S O], the expression [S (S O)], the expression
    [S (S (S O))], and so on all belong to the set [nat], while other
    expressions like [true], [andb true false], and [S (S false)] do
    not.

    We can write simple functions that pattern match on natural
    numbers just as we did above -- for example, predecessor: *)

Definition pred (n : nat) : nat :=
  match n with
    | O => O
    | S n' => n'
  end.

(** The second branch can be read: "if [n] has the form [S n']
    for some [n'], then return [n']."  *)

End Playground1.

Definition minustwo (n : nat) : nat :=
  match n with
    | O => O
    | S O => O
    | S (S n') => n'
  end.

(** Because natural numbers are such a pervasive form of data,
    Coq provides a tiny bit of built-in magic for parsing and printing
    them: ordinary arabic numerals can be used as an alternative to
    the "unary" notation defined by the constructors [S] and [O].  Coq
    prints numbers in arabic form by default: *)

Check (S (S (S (S O)))).
Eval simpl in (minustwo 4).

(** The constructor [S] has the type [nat -> nat], just like the
    functions [minustwo] and [pred]: *)

Check S.
Check pred.
Check minustwo.

(** These are all things that can be applied to a number to yield a
    number.  However, there is a fundamental difference: functions
    like [pred] and [minustwo] come with _computation rules_
    -- e.g., the definition of [pred] says that [pred n] can be
    simplified to [match n with | O => O | S m' => m' end] -- while
    the definition of [S] has no such behavior attached.  Although it
    is like a function in the sense that it can be applied to an
    argument, it does not _do_ anything at all! *)

(** For most function definitions over numbers, pure pattern
    matching is not enough: we also need recursion.  For example, to
    check that a number [n] is even, we may need to recursively check
    whether [n-2] is even.  To write such functions, we use the
    keyword [Fixpoint]. *)

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

(** We can define [oddb] by a similar [Fixpoint] declaration, but here
    is a simpler definition that will be a bit easier to work with: *)

Definition oddb (n:nat) : bool   :=   negb (evenb n).

Example test_oddb1:    (oddb (S O)) = true.
Proof. simpl. reflexivity.  Qed.
Example test_oddb2:    (oddb (S (S (S (S O))))) = false.
Proof. simpl. reflexivity.  Qed.

(** Naturally, we can also define multi-argument functions by
    recursion.  (Once again, we use a module to avoid polluting the
    namespace.) *)

Module Playground2.

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

(** Adding three to two now gives us five, as we'd expect. *)

Eval simpl in (plus (S (S (S O))) (S (S O))).

(** The simplification that Coq performs to reach this conclusion can
    be visualized as follows: *)

(*  [plus (S (S (S O))) (S (S O))]
==> [S (plus (S (S O)) (S (S O)))] by the second clause of the [match]
==> [S (S (plus (S O) (S (S O))))] by the second clause of the [match]
==> [S (S (S (plus O (S (S O)))))] by the second clause of the [match]
==> [S (S (S (S (S O))))]          by the first clause of the [match]
*)

(** As a notational convenience, if two or more arguments have
    the same type, they can be written together.  In the following
    definition, [(n m : nat)] means just the same as if we had written
    [(n : nat) (m : nat)]. *)

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

Example test_mult1: (mult 3 3) = 9.
Proof. simpl. reflexivity.  Qed.

(** You can match two expressions at once by putting a comma
    between them: *)

Fixpoint minus (n m:nat) : nat :=
  match n, m with
  | O   , _    => O
  | S _ , O    => n
  | S n', S m' => minus n' m'
  end.

(** The _ in the first line is a _wildcard pattern_.  Writing _ in a
    pattern is the same as writing some variable that doesn't get used
    on the right-hand side.  This avoids the need to invent a bogus
    variable name. *)

End Playground2.

Fixpoint exp (base power : nat) : nat :=
  match power with
    | O => S O
    | S p => mult base (exp base p)
  end.

(** **** Exercise: 1 star (factorial) *)
(** Recall the standard factorial function:
<<
    factorial(0)  =  1
    factorial(n)  =  n * factorial(n-1)     (if n>0)
>>
    Translate this into Coq. *)

Fixpoint factorial (n:nat) : nat :=
(* FILL IN HERE *)
  match n with
      | O => 1
      | S n' => mult n (factorial n')
  end.
Example test_factorial1:          (factorial 3) = 6.
Proof. simpl. reflexivity. Qed.
(* FILL IN HERE *)

Example test_factorial2:          (factorial 5) = (mult 10 12).
(* FILL IN HERE *) Proof. simpl. reflexivity. Qed.
(** [] *)

(** We can make numerical expressions a little easier to read and
    write by introducing "notations" for addition, multiplication, and
    subtraction. *)

Notation "x + y" := (plus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x - y" := (minus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x * y" := (mult x y)
                       (at level 40, left associativity)
                       : nat_scope.

Check ((0 + 1) + 1).

(** (The [level], [associativity], and [nat_scope] annotations
   control how these notations are treated by Coq's parser.  The
   details are not important, but interested readers can refer to the
   "More on Notation" subsection in the "Optional Material" section at
   the end of this chapter.) *)

(** Note that these do not change the definitions we've already
    made: they are simply instructions to the Coq parser to accept [x
    + y] in place of [plus x y] and, conversely, to the Coq
    pretty-printer to display [plus x y] as [x + y]. *)

(** When we say that Coq comes with nothing built-in, we really
    mean it: even equality testing for numbers is a user-defined
    operation! *)
(** The [beq_nat] function tests [nat]ural numbers for [eq]uality,
    yielding a [b]oolean.  Note the use of nested [match]es (we could
    also have used a simultaneous match, as we did in [minus].)  *)

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.

(** Similarly, the [ble_nat] function tests [nat]ural numbers for
    [l]ess-or-[e]qual, yielding a [b]oolean. *)

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.

Example test_ble_nat1:             (ble_nat 2 2) = true.
Proof. simpl. reflexivity.  Qed.
Example test_ble_nat2:             (ble_nat 2 4) = true.
Proof. simpl. reflexivity.  Qed.
Example test_ble_nat3:             (ble_nat 4 2) = false.
Proof. simpl. reflexivity.  Qed.

(** **** Exercise: 2 stars (blt_nat) *)
(** The [blt_nat] function tests [nat]ural numbers for [l]ess-[t]han,
    yielding a [b]oolean.  Instead of making up a new [Fixpoint] for
    this one, define it in terms of a previously defined function.

    Note: If you have trouble with the [simpl] tactic, try using
    [compute], which is like [simpl] on steroids.  However, there is a
    simple, elegant solution for which [simpl] suffices. *)

Definition blt_nat (n m : nat) : bool :=
  match m with
  | O => false
  | S m' => ble_nat n (minus m 1)
  end.

Example test_blt_nat1:             (blt_nat 2 2) = false.
(* FILL IN HERE *) simpl. reflexivity. Qed.
Example test_blt_nat2:             (blt_nat 2 4) = true.
(* FILL IN HERE *) compute. reflexivity. Qed.
Example test_blt_nat3:             (blt_nat 4 2) = false.
(* FILL IN HERE *) simpl. reflexivity. Qed.
(** [] *)

(* ###################################################################### *)
(** * Proof By Simplification *)

(** Now that we've defined a few datatypes and functions, let's
    turn to the question of how to state and prove properties of their
    behavior.  Actually, in a sense, we've already started doing this:
    each [Example] in the previous sections makes a precise claim
    about the behavior of some function on some particular inputs.
    The proofs of these claims were always the same: use the
    function's definition to simplify the expressions on both sides of
    the [=] and notice that they become identical.

    The same sort of "proof by simplification" can be used to prove
    more interesting properties as well.  For example, the fact that
    [0] is a "neutral element" for [+] on the left can be proved
    just by observing that [0 + n] reduces to [n] no matter what
    [n] is, since the definition of [+] is recursive in its first
    argument. *)

Theorem plus_O_n : forall n : nat, 0 + n = n.
Proof.
  simpl. reflexivity.  Qed.

(** The form of this theorem and proof are almost exactly the
    same as the examples above: the only differences are that we've
    added the quantifier [forall n:nat] and that we've used the
    keyword [Theorem] instead of [Example].  Indeed, the latter
    difference is purely a matter of style; the keywords [Example] and
    [Theorem] (and a few others, including [Lemma], [Fact], and
    [Remark]) mean exactly the same thing to Coq.

    The keywords [simpl] and [reflexivity] are examples of _tactics_.
    A tactic is a command that is used between [Proof] and [Qed] to
    tell Coq how it should check the correctness of some claim we are
    making.  We will see several more tactics in the rest of this
    lecture, and yet more in future lectures. *)

(** The [reflexivity] command implicitly simplifies both sides of the
    equality before testing to see if they are the same, so we can
    shorten the proof a little. *)
(** (It will be useful later to know that [reflexivity] actually
    does somewhat more than [simpl] -- for example, it tries
    "unfolding" defined terms, replacing them with their right-hand
    sides.  The reason for this difference is that, when reflexivity
    succeeds, the whole goal is finished and we don't need to look at
    whatever expanded expressions [reflexivity] has found; by
    contrast, [simpl] is used in situations where we may have to read
    and understand the new goal, so we would not want it blindly
    expanding definitions.) *)

Theorem plus_O_n' : forall n:nat, 0 + n = n.
Proof.
  reflexivity.  Qed.

(** **** Exercise: 1 star, optional (simpl_plus) *)
(** What will Coq print in response to this query? *)

(* Eval simpl in (forall n:nat, n + 0 = n). *)

(** What about this one? *)

(* Eval simpl in (forall n:nat, 0 + n = n). *)

(** Explain the difference.  [] *)

(* ###################################################################### *)
(** * The [intros] Tactic *)

(** Aside from unit tests, which apply functions to particular
    arguments, most of the properties we will be interested in proving
    about programs will begin with some quantifiers (e.g., "for all
    numbers [n], ...") and/or hypothesis ("assuming [m=n], ...").  In
    such situations, we will need to be able to reason by _assuming
    the hypothesis_ -- i.e., we start by saying "OK, suppose [n] is
    some arbitrary number," or "OK, suppose [m=n]."

    The [intros] tactic permits us to do this by moving one or more
    quantifiers or hypotheses from the goal to a "context" of current
    assumptions.

    For example, here is a slightly different proof of the same theorem. *)

Theorem plus_O_n'' : forall n:nat, 0 + n = n.
Proof.
  intros n. reflexivity.  Qed.

(** Step through this proof in Coq and notice how the goal and
    context change. *)

Theorem plus_1_l : forall n:nat, 1 + n = S n.
Proof.
  intros n. reflexivity.  Qed.

Theorem mult_0_l : forall n:nat, 0 * n = 0.
Proof.
  intros n. reflexivity.  Qed.

(** The [_l] suffix in the names of these theorems is
    pronounced "on the left." *)

(* ###################################################################### *)
(** * Proof by Rewriting *)

(** Here is a slightly more interesting theorem: *)

Theorem plus_id_example : forall n m:nat,
  n = m ->
  n + n = m + m.

(** Instead of making a completely universal claim about all numbers
    [n] and [m], this theorem talks about a more specialized property
    that only holds when [n = m].  The arrow symbol is pronounced
    "implies."

    Since [n] and [m] are arbitrary numbers, we can't just use
    simplification to prove this theorem.  Instead, we prove it by
    observing that, if we are assuming [n = m], then we can replace
    [n] with [m] in the goal statement and obtain an equality with the
    same expression on both sides.  The tactic that tells Coq to
    perform this replacement is called [rewrite]. *)

Proof.
  intros n m.   (* move both quantifiers into the context *)
  intros H.     (* move the hypothesis into the context *)
  rewrite -> H. (* Rewrite the goal using the hypothesis *)
  reflexivity.  Qed.

(** The first line of the proof moves the universally quantified
    variables [n] and [m] into the context.  The second moves the
    hypothesis [n = m] into the context and gives it the name [H].
    The third tells Coq to rewrite the current goal ([n + n = m + m])
    by replacing the left side of the equality hypothesis [H] with the
    right side.

    (The arrow symbol in the [rewrite] has nothing to do with
    implication: it tells Coq to apply the rewrite from left to right.
    To rewrite from right to left, you can use [rewrite <-].  Try
    making this change in the above proof and see what difference it
    makes in Coq's behavior.) *)

(** **** Exercise: 1 star (plus_id_exercise) *)
(** Remove "[Admitted.]" and fill in the proof. *)

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.
intros n m o.
intros H1 H2.
rewrite -> H1.
rewrite -> H2.
reflexivity.
Qed.
  (* FILL IN HERE *)
(** [] *)

(** As we've seen in earlier examples, the [Admitted] command
    tells Coq that we want to skip trying to prove this theorem and
    just accept it as a given.  This can be useful for developing
    longer proofs, since we can state subsidiary facts that we believe
    will be useful for making some larger argument, use [Admitted] to
    accept them on faith for the moment, and continue thinking about
    the larger argument until we are sure it makes sense; then we can
    go back and fill in the proofs we skipped.  Be careful, though:
    every time you say [Admitted] (or [admit]) you are leaving a door
    open for total nonsense to enter Coq's nice, rigorous, formally
    checked world! *)

(** We can also use the [rewrite] tactic with a previously proved
    theorem instead of a hypothesis from the context. *)

Theorem mult_0_plus : forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  rewrite -> plus_O_n.
  reflexivity.  Qed.

(** **** Exercise: 2 stars (mult_1_plus) *)
Theorem mult_1_plus : forall n m : nat,
  (1 + n) * m = m + (n * m).
Proof.
intros n m.
simpl. reflexivity. Qed.
(*TODO use rewrite? *)
  (* FILL IN HERE *) (** [] *)

(* ###################################################################### *)
(** * Proof by Case Analysis *)

(** Of course, not everything can be proved by simple
    calculation: In general, unknown, hypothetical values (arbitrary
    numbers, booleans, lists, etc.) can block the calculation.
    For example, if we try to prove the following fact using the
    [simpl] tactic as above, we get stuck. *)

Theorem plus_1_neq_0_firsttry : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n.
  simpl.  (* does nothing! *)
Admitted.

(** The reason for this is that the definitions of both
    [beq_nat] and [+] begin by performing a [match] on their first
    argument.  But here, the first argument to [+] is the unknown
    number [n] and the argument to [beq_nat] is the compound
    expression [n + 1]; neither can be simplified.

    What we need is to be able to consider the possible forms of [n]
    separately.  If [n] is [O], then we can calculate the final result
    of [beq_nat (n + 1) 0] and check that it is, indeed, [false].
    And if [n = S n'] for some [n'], then, although we don't know
    exactly what number [n + 1] yields, we can calculate that, at
    least, it will begin with one [S], and this is enough to calculate
    that, again, [beq_nat (n + 1) 0] will yield [false].

    The tactic that tells Coq to consider, separately, the cases where
    [n = O] and where [n = S n'] is called [destruct]. *)

Theorem plus_1_neq_0 : forall n : nat,
  beq_nat (n + 1) 0 = false.
Proof.
  intros n. destruct n as [| n'].
    reflexivity.
    reflexivity.  Qed.

(** The [destruct] generates _two_ subgoals, which we must then
    prove, separately, in order to get Coq to accept the theorem as
    proved.  (No special command is needed for moving from one subgoal
    to the other.  When the first subgoal has been proved, it just
    disappears and we are left with the other "in focus.")  In this
    proof, each of the subgoals is easily proved by a single use of
    [reflexivity].

    The annotation "[as [| n']]" is called an _intro pattern_.  It
    tells Coq what variable names to introduce in each subgoal.  In
    general, what goes between the square brackets is a _list_ of
    lists of names, separated by [|].  Here, the first component is
    empty, since the [O] constructor is nullary (it doesn't carry any
    data).  The second component gives a single name, [n'], since [S]
    is a unary constructor.

    The [destruct] tactic can be used with any inductively defined
    datatype.  For example, we use it here to prove that boolean
    negation is involutive -- i.e., that negation is its own
    inverse. *)

Theorem negb_involutive : forall b : bool,
  negb (negb b) = b.
Proof.
  intros b. destruct b.
    reflexivity.
    reflexivity.  Qed.

(** Note that the [destruct] here has no [as] clause because
    none of the subcases of the [destruct] need to bind any variables,
    so there is no need to specify any names.  (We could also have
    written [as [|]], or [as []].)  In fact, we can omit the [as]
    clause from _any_ [destruct] and Coq will fill in variable names
    automatically.  Although this is convenient, it is arguably bad
    style, since Coq often makes confusing choices of names when left
    to its own devices. *)

(** **** Exercise: 1 star (zero_nbeq_plus_1) *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  beq_nat 0 (n + 1) = false.
Proof.
  (* FILL IN HERE *) intros n. destruct n as [ |n']. reflexivity. reflexivity. Qed.
(** [] *)

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

(** **** Exercise: 2 stars (boolean functions) *)
(** Use the tactics you have learned so far to prove the following
    theorem about boolean functions. *)

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof. intro. intro. intro. rewrite -> H. rewrite -> H. reflexivity. Qed.
  (* FILL IN HERE *)

(** Now state and prove a theorem [negation_fn_applied_twice] similar
    to the previous one but where the second hypothesis says that the
    function [f] has the property that [f x = negb x].*)

(* FILL IN HERE *)

(** **** Exercise: 2 stars (andb_eq_orb) *)
(** Prove the following theorem.  (You may need to first prove a
    subsidiary lemma or two.) *)

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  (* FILL IN HERE *) intro. intro. destruct b. destruct c.
simpl.   reflexivity.
simpl. intro.  rewrite -> H. reflexivity.
destruct c.
simpl. intro. rewrite -> H. reflexivity.
simpl.  reflexivity. Qed.
(** **** Exercise: 3 stars (binary) *)
(** Consider a different, more efficient representation of natural
    numbers using a binary rather than unary system.  That is, instead
    of saying that each natural number is either zero or the successor
    of a natural number, we can say that each binary number is either

      - zero,
      - twice a binary number, or
      - one more than twice a binary number.

    (a) First, write an inductive definition of the type [bin]
        corresponding to this description of binary numbers.

    (Hint: Recall that the definition of [nat] from class,
    Inductive nat : Type :=
      | O : nat
      | S : nat -> nat.
    says nothing about what [O] and [S] "mean."  It just says "[O] is
    in the set called [nat], and if [n] is in the set then so is [S
    n]."  The interpretation of [O] as zero and [S] as successor/plus
    one comes from the way that we _use_ [nat] values, by writing
    functions to do things with them, proving things about them, and
    so on.  Your definition of [bin] should be correspondingly simple;
    it is the functions you will write next that will give it
    mathematical meaning.)

    (b) Next, write an increment function for binary numbers, and a
        function to convert binary numbers to unary numbers.

    (c) Write some unit tests for your increment and binary-to-unary
        functions. Notice that incrementing a binary number and
        then converting it to unary should yield the same result as first
        converting it to unary and then incrementing.
*)

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

(* ###################################################################### *)
(** * Optional Material *)

(** ** More on Notation *)

Notation "x + y" := (plus x y)
                       (at level 50, left associativity)
                       : nat_scope.
Notation "x * y" := (mult x y)
                       (at level 40, left associativity)
                       : nat_scope.

(**
    For each notation-symbol in Coq we can specify its _precedence level_
    and its _associativity_. The precedence level n can be specified by the
    keywords [at level n] and it is helpful to disambiguate
    expressions containing different symbols. The associativity is helpful
    to disambiguate expressions containing more occurrences of the same
    symbol. For example, the parameters specified above for [+] and [*]
    say that the expression [1+2*3*4] is a shorthand for the expression
    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and
    _left_, _right_, or _no_ associativity.

    Each notation-symbol in Coq is also active in a _notation scope_.
    Coq tries to guess what scope you mean, so when you write [S(O*O)]
    it guesses [nat_scope], but when you write the cartesian
    product (tuple) type [bool*bool] it guesses [type_scope].
    Occasionally you have to help it out with percent-notation by
    writing [(x*y)%nat], and sometimes in Coq's feedback to you it
    will use [%nat] to indicate what scope a notation is in.

    Notation scopes also apply to numeral notation (3,4,5, etc.), so you
    may sometimes see [0%nat] which means [O], or [0%Z] which means the
    Integer zero.
*)

(** ** [Fixpoint]s and Structural Recursion *)

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

(** When Coq checks this definition, it notes that [plus'] is
    "decreasing on 1st argument."  What this means is that we are
    performing a _structural recursion_ over the argument [n] -- i.e.,
    that we make recursive calls only on strictly smaller values of
    [n].  This implies that all calls to [plus'] will eventually
    terminate.  Coq demands that some argument of _every_ [Fixpoint]
    definition is "decreasing".

    This requirement is a fundamental feature of Coq's design: In
    particular, it guarantees that every function that can be defined
    in Coq will terminate on all inputs.  However, because Coq's
    "decreasing analysis" is not very sophisticated, it is sometimes
    necessary to write functions in slightly unnatural ways. *)

(** **** Exercise: 2 stars, optional (decreasing) *)
(** To get a concrete sense of this, find a way to write a sensible
    [Fixpoint] definition (of a simple function on numbers, say) that
    _does_ terminate on all inputs, but that Coq will _not_ accept
    because of this restriction. *)

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

(* $Date: 2013-01-09 14:02:50 -0500 (Wed, 09 Jan 2013) $ *)


Load MyLists.

Search (nat -> nat -> bool).

Fixpoint count (v:nat) (s:bag) : nat :=
  match s with
  | []        => 0
  | cons x s' => match (Nat.eqb x v) with
                | true  => 1 + (count v s')
                | false => count v s'
                end
  end.

Example test_count1: count 1 [1;2;3;1;4;1] = 3.
Proof.
  simpl.
  reflexivity.
Qed.

Example test_count2: count 6 [1;2;3;1;4;1] = 0.
Proof.
  simpl.
  reflexivity.
Qed.

Definition sum : bag -> bag -> bag := app.

Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.
Proof.
  simpl.
  reflexivity.
Qed.

Definition add (v:nat) (s:bag) : bag := cons v s.

Example test_add1: count 1 (add 1 [1;4;1]) = 3.
Proof.
  simpl.
  reflexivity.
Qed.

Example test_add2: count 5 (add 1 [1;4;1]) = 0.
Proof.
  simpl.
  reflexivity.
Qed.

Definition member (v:nat) (s:bag) : bool := negb (Nat.leb (count v s) 0).

Example test_member1: member 1 [1;4;1] = true.
Proof.
  simpl.
  reflexivity.
Qed.

Example test_member2: member 2 [1;4;1] = false.
Proof.
  simpl.
  reflexivity.
Qed.


(** *Monoids.

An implementation of monoids.

 *)

(* Lists in the standard library are not universe
   polymorphic. This does not work well with the
   `call` element of the Verse AST
*)
Require Import Monoid.PList.
Require Export SetoidClass.
Require Export Setoid.
Require Import RelationClasses.
Require Export Relation_Definitions.

(* TODO : Move eq_setoid and its setoids monoids to the bottom of the
          file. Will avoid errors like that happened with
          dep_point_monoid
*)

Class BinOp (t : Type) := binop : t -> t -> t.
Infix "**" := binop (right associativity, at level 60).

Class Monoid t `{Setoid t} `{BinOp t}
  := { ε  : t;
       proper_oper    : Proper (SetoidClass.equiv ==> SetoidClass.equiv ==> SetoidClass.equiv) binop;
       left_identity  : forall x : t, (ε ** x) == x;
       right_identity : forall x : t, (x ** ε) == x;
       associativity  : forall x y z : t,
           (x ** (y ** z)) == ((x ** y) ** z)
     }.

Ltac intro_destruct := let x := fresh "x" in (intro x; destruct x; simpl).

Ltac crush_monoid :=
  repeat match goal with
         | [ H1 : False |- _ ] => intuition
         | [ _ :  _ = ?X,  _ : ?X = _ |- _ = _ ] => intros; transitivity X; eauto
         | [ _ :  _ == ?X,  _ : ?X == _ |- _ == _ ] => intros; transitivity X; eauto
         | [ H : ?X == _ |- context[?X] ] => rewrite H
         | [ |- context[ε] ] => try (rewrite left_identity); try (rewrite right_identity)
         | _ => intuition; try (apply associativity)
         | [ |- _ == _ ] => try (rewrite symmetry)
         end.

Ltac crush_morph_tac n :=
  do n (do 2 intro_destruct; let hyp := fresh "eqhyp" in intro hyp); crush_monoid.

Tactic Notation "crush_morph" integer(n) := (crush_morph_tac n).

(** It should be possible to rewrite with monoid equivalence and
    operation. For this we register the underlying setoid equivalence
    and declare the monoid operation as a morphism *)

Add Parametric Relation T  (tsetoid : Setoid T)(bop : BinOp T)`{ _ : @Monoid T tsetoid bop} : T  (SetoidClass.equiv)
    reflexivity proved by (setoid_refl tsetoid)
    symmetry proved by (setoid_sym (sa:=tsetoid) )
    transitivity proved by (setoid_trans (sa:=tsetoid) ) as monoid_equivalence.

Add Parametric Morphism T `{Monoid T} : binop with signature
    (SetoidClass.equiv ==> SetoidClass.equiv ==> SetoidClass.equiv) as binop_mor.
Proof.
  exact proper_oper.
Qed.

Fixpoint ntimes {t} `{Monoid t} n T
  := match n with
     | 0   => ε
     | S m => T ** ntimes m T
     end.

Definition mconcat {t}`{mon: Monoid t} : list t -> t
  := fun l => fold_left binop l ε.

Add Parametric Morphism {t} `{Monoid t} (l : list t) : (fold_left binop l)
    with signature (SetoidClass.equiv ==> SetoidClass.equiv) as foldleft_mor.
Proof.
  induction l; intros x y eqxy.
  * trivial.
  * apply IHl.
    crush_monoid.
Qed.

Definition mapMconcat {A}{t}`{mon : Monoid t}
           (f : A -> t) (xs : list A)
  : t
  := mconcat (map f xs).

Lemma foldleft_init {t}`{mon: Monoid t} l i1 i2 :
  fold_left binop l (i1 ** i2) == i1 ** fold_left binop l i2.
Proof.
  revert i1 i2.
  induction l; intro i.
  * simpl.
    crush_monoid.
  * simpl.
    intro.
    rewrite <- associativity.
    apply IHl.
Qed.

Lemma mapMconcat_app {A}{t}`{mon : Monoid t}
      (f : A -> t) l1 l2
  : mapMconcat f (l1 ++ l2) == mapMconcat f l1 ** mapMconcat f l2.
Proof.
  unfold mapMconcat, mconcat.
  rewrite map_app.
  rewrite fold_left_app.
  induction l2.
  * simpl.
    now crush_monoid.
  * simpl.
    rewrite left_identity.
    apply foldleft_init.
Qed.

Lemma mapMconcat_cons {A}{t}`{mon : Monoid t}
      (f : A -> t) a l
  : mapMconcat f (a :: l) == f a ** mapMconcat f l.
Proof.
  unfold mapMconcat, mconcat.
  rewrite map_cons.
  simpl.
  rewrite left_identity.
  rewrite <- (right_identity (f a)).
  rewrite foldleft_init.
  now rewrite right_identity.
Qed.

(** ** State transition.

Transitions over a state space are just functions and can be given a
monoid structure. In the context of state transition it is more
natural to define the monoid multiplication in terms of the reverse
composition. We define a new notation for this and define the monoid
instance.

*)

(* begin hide *)
Require Import Basics.
(* end hide *)

Notation "f >-> g" := (compose g f) (left associativity, at level 40).

(** Now for the laws of monoid *)

Module LawsTransition.
  Definition left_identity_compose : forall A (f : A -> A),  (@id A) >-> f = f.
    trivial.
  Qed.

  Definition right_identity_compose : forall A (f : A -> A),  f >-> (@id A)  = f.
    trivial.
  Qed.

  Definition assoc_compose : forall A (f g h : A -> A), f >-> (g >-> h) = (f >-> g) >-> h.
    trivial.
  Qed.

  Definition assoc_compose' : forall A (f g h : A -> A), (h >-> g) >-> f = h >-> (g >-> f).
    trivial.
  Qed.

End LawsTransition.

Import LawsTransition.

Section FunctionEquivalence.
  Context {B : Type}`{Setoid B}{A : Type}.
  Definition equiv_function : relation (A -> B) := fun (f g : A -> B) => forall x, f x == g x.
  Lemma equiv_function_refl : reflexive _ equiv_function.
    intros f x. reflexivity.
  Qed.

  Lemma equiv_function_symm : symmetric _ equiv_function.
    intros f g fEg x.
    symmetry; eauto.
  Qed.

  Lemma equiv_function_transitive : transitive _ equiv_function.
    intros f g h fEg gEh x; transitivity (g x); eauto.
  Qed.

  Global Add Parametric Relation : (A -> B) equiv_function
    reflexivity proved by equiv_function_refl
    symmetry proved by equiv_function_symm
    transitivity proved by equiv_function_transitive
  as function_equivalence.

End FunctionEquivalence.

#[global] Instance function_setoid B `{Setoid B} A : Setoid (A -> B) | 1 :=
  {| SetoidClass.equiv := equiv_function;
     setoid_equiv := function_equivalence
  |}.

Section FunctionEquivalence.
  Context {B : Type}`{Monoid B}{A : Type}.
  Definition function_product (f g : A -> B) : A -> B := fun x => f x ** g x.

  Global Add Parametric Morphism : function_product with signature
      (SetoidClass.equiv ==> SetoidClass.equiv ==> SetoidClass.equiv) as function_product_mor.
  Proof.
    intros f g fEQg fp gp fEQgP; intro.
    unfold function_product. rewrite (fEQg x). rewrite (fEQgP x); reflexivity.
  Qed.

End FunctionEquivalence.

#[global] Instance function_binop A B `{Monoid B} : BinOp (A -> B) :=
  fun f g x => f x ** g x.

#[global] Program Instance function_monoid A B `{Monoid B} : Monoid (A -> B) | 1 :=
  {| ε              := fun _ => ε;
     proper_oper    := function_product_mor_Proper;
     left_identity  := _;
     right_identity := _;
     associativity  := _;
  |}.

Next Obligation.
  unfold equiv_function; intros;apply left_identity.
Qed.

Next Obligation.
  unfold equiv_function; intros; apply right_identity.
Qed.

Next Obligation.
  unfold equiv_function.
  intros. apply associativity.
Qed.

(* TODO *)
#[global] Instance dep_point_setoid A (F : A -> Type)
         `{forall a, Setoid (F a)}
  : Setoid (forall a, F a) | 2 :=
  {| SetoidClass.equiv f g := forall x, f x == g x;
     setoid_equiv := {|
                      Equivalence_Reflexive := fun f a =>
                                                 reflexivity (f a);
                      Equivalence_Symmetric := fun (f g : forall a, F a)
                                                   (H :
                                                      forall a : A,
                                                        f a == g a)
                                                   (a : A) =>
                                                 symmetry (H a);
                      Equivalence_Transitive := fun (f g h : forall a, F a)
                                                    (Hfg :
                                                       forall a : A,
                                                         (f a == g a))
                                                    (Hgh :
                                                       forall a : A,
                                                         (g a == h a))
                                                    (a : A) =>
                                                  transitivity (Hfg a) (Hgh a)
                    |}
  |}.

#[global] Instance dep_point_binop  A (F : A -> Type)
         `{forall a, BinOp (F a)}
  : BinOp (forall a, F a) := fun f g => fun a => f a ** g a.

Add Parametric Morphism A (F : A -> Type)
    `{forall a, Setoid (F a)}
    `{forall a, BinOp (F a)}
    `{forall a, Proper (SetoidClass.equiv (A := F a) ==> SetoidClass.equiv ==> SetoidClass.equiv) binop}

  : binop  with signature
    SetoidClass.equiv (A := forall a, F a) ==> SetoidClass.equiv ==> SetoidClass.equiv
      as dep_point_binop_mor.
  intros f g. simpl.
  intro fEg.
  intros h k. simpl.
  intro hEk.
  intro x. unfold binop. unfold dep_point_binop.
  rewrite (fEg x).
  rewrite (hEk x).
  reflexivity.
Qed.

#[global] Program Instance dep_point_monoid A (F : A -> Type)
         `{forall a, Setoid (F a)}
         `{forall a, BinOp (F a)}
         `{forall a, Monoid (F a)}
  : Monoid (forall a, F a) | 2
                          := {| ε := fun _ => ε;
                                left_identity  := _;
                                right_identity := _;
                                associativity  := _;
                             |}.
Next Obligation.
  unfold binop. unfold dep_point_binop. crush_monoid.
Qed.

Next Obligation.
  unfold binop. unfold dep_point_binop. crush_monoid.
Qed.

Next Obligation.
  unfold binop. unfold dep_point_binop. crush_monoid.
Qed.

Class Hom [t1 t2]`{Monoid t1} `{Monoid t2} (f : t1 -> t2) : Prop
  := { proper_morphism  : Proper (SetoidClass.equiv ==> SetoidClass.equiv) f;
       preserves_unit      : f ε == ε;
       preserves_product   : forall {a b}, f (a ** b) == f a ** f b
     }.

#[global] Instance monoid_homomorphism_Proper t1 t2 (f : t1 -> t2) `{Hom t1 t2 f} : Proper (SetoidClass.equiv ==> SetoidClass.equiv) f
  := proper_morphism.

Arguments preserves_unit [t1 t2] {_ _ _ _ _} _.
Arguments preserves_product [t1 t2] {_ _ _ _ _} _.

(**

Monoidal version of concat. The function [mconcat] takes a list of
elements in the monoid and multiplies them to get the results

 *)

(**  * Monoid instance A + {E}.

*)

Require Import Verse.Error.

Section Error.
  Context {E : Prop}{A : Type}`{Monoid A}.

  Definition eq_error (x y : A + {E}) : Prop :=
    match x , y with
    | error xe, error ye => xe = ye
    | {- xa -}, {- ya -} => xa == ya
    | _, _               => False
    end.

  Lemma eq_error_refl : Reflexive eq_error.
  Proof.
    intro; destruct x; simpl; reflexivity.
  Qed.

  Lemma eq_error_sym : Symmetric  eq_error.
  Proof.
    intros x y; destruct x; destruct y; simpl;
      repeat intuition.
  Qed.

  Lemma eq_error_trans : Transitive eq_error.
  Proof.
    do 3 intro_destruct; crush_monoid.
  Qed.

  Global Add Parametric Relation : (A + {E}) eq_error
      reflexivity proved by eq_error_refl
      symmetry proved by eq_error_sym
      transitivity proved by eq_error_trans as error_equivalence.

  #[global] Instance error_setoid : Setoid (A + {E}) :=
    {| SetoidClass.equiv :=  eq_error;
       SetoidClass.setoid_equiv := error_equivalence
    |}.

  Definition error_prod (x y : A + {E}) : A + {E} :=
    match x, y with
    | {- a -}, {- b -}  => {- a ** b -}
    | error e, _       => error e
    | _      , error e => error e
    end.

  Global Add Parametric Morphism : error_prod with signature
      (eq_error ==> eq_error ==> eq_error) as error_prod_mor.
  Proof.
    crush_morph 2.
  Qed.

  #[global] Instance binop_error : BinOp (A + {E}) := error_prod.

  Global Program Instance error_monoid
  : Monoid (A + {E}) :=
  {| ε := {- ε -};
     left_identity := _;
     right_identity := _;
     associativity := _;
  |}.

  Next Obligation.
    destruct x; simpl; trivial; apply left_identity.
  Qed.
  Next Obligation.
    destruct x; simpl; trivial; apply right_identity.
  Qed.

  Next Obligation.
    destruct x; destruct y; destruct z; simpl; trivial;apply associativity.
  Qed.

End Error.

Section Prod.

  Context (A B : Type)`{Monoid A} `{Monoid B}.
  Definition eq_prod (x y : A * B) := (fst x == fst y) /\ (snd x == snd y).

  Definition eq_prod_refl : Reflexive eq_prod
      := fun x => conj (Equivalence_Reflexive (fst x)) (Equivalence_Reflexive (snd x)).

  Definition eq_prod_symm : Symmetric eq_prod
      := fun x y r => let (rf, rs) := r in
                      conj (Equivalence_Symmetric _ _ rf)
                           (Equivalence_Symmetric _ _ rs).

  Definition eq_prod_trans : Transitive eq_prod
      := fun x y z rxy ryz =>
               let (rxyf, rxys) := rxy in
               let (ryzf, ryzs) := ryz in
               conj (Equivalence_Transitive _ _ _ rxyf ryzf)
                    (Equivalence_Transitive _ _ _ rxys ryzs).

  Add Parametric Relation : (A * B)%type  eq_prod
      reflexivity proved by eq_prod_refl
      symmetry proved by eq_prod_symm
      transitivity proved by eq_prod_trans as prod_equivalence.

  #[global] Instance prod_setoid  : Setoid (A * B)
    := {| SetoidClass.equiv        := eq_prod; |}.

  #[global] Instance prod_binop : BinOp (A * B) := fun x y => (fst x ** fst y, snd x ** snd y).

  Global Add Parametric Morphism : binop with signature
      eq_prod ==> eq_prod ==> eq_prod
        as product_binop_mor.
    unfold eq_prod.
    crush_morph 2.
  Qed.

  Global Program Instance prod_monoid : Monoid (A * B) :=
    {| ε := (ε, ε);
       left_identity := _;
       right_identity := _;
       associativity := _
    |}.
  Next Obligation.
    unfold eq_prod; simpl; crush_monoid.
  Qed.

  Next Obligation.
    unfold eq_prod; simpl; crush_monoid.
  Qed.

  Next Obligation.
    unfold eq_prod; simpl; crush_monoid.
  Qed.

End Prod.
Class LActionOp G A := lact : G -> A -> A.

Infix "•" := (lact) (right associativity, at level 58).

(* TODO MAYBE:

One can also capture right action but since our application is for
transforms acting on state predicates, we only capture left actions
as of now

<<

Class RActionOp A G := ract : A -> G -> A.
Infix "↑" := (ract) (left associativity, at level 59).

>>

 *)

Class LAction G A `{Monoid A}`{Monoid G}`{LActionOp G A} :=
  { proper_laction
    : Proper (SetoidClass.equiv (A:=G) ==> SetoidClass.equiv (A:=A) ==> SetoidClass.equiv (A:=A)) lact;
    lact_unit                : forall g, g•ε == ε;
    lact_preserve_product  : forall g a1 a2, g•(a1 ** a2) == g•a1 ** g•a2;
    lact_trivial           : forall a, ε•a == a;
    lact_compose           : forall g1 g2 a, (g1 ** g2)•a  == g1•g2•a
  }.

#[global] Instance monoid_action_Proper G A `{LAction G A}
  : Proper (SetoidClass.equiv (A:=G) ==> SetoidClass.equiv (A:=A) ==> SetoidClass.equiv(A:=A)) lact
  := proper_laction.

Inductive SemiR G A := semiR : G -> A -> SemiR G A.
Infix "⋉" := SemiR (left associativity, at level 59).

Definition srFst [G A] (sr : SemiR G A) := let (g, _) := sr in g.
Definition srSnd [G A] (sr : SemiR G A) := let (_, a) := sr in a.

Arguments semiR {G A}.

Section SemiDirectProduct.

  Context {G A : Type}
          `{LAction G A}.

  Definition eqSemiR (s1 s2 : G ⋉ A) :=
    match s1, s2 with
    | semiR g1 a1, semiR g2 a2 =>
        g1 == g2 /\ a1 == a2
    end.

  Definition eqsemi_refl : Reflexive eqSemiR.
    unfold Reflexive.
    intro_destruct. crush_monoid.
  Qed.

  Definition eqsemi_sym : Symmetric eqSemiR.
    unfold Symmetric.
    do 2 intro_destruct; crush_monoid.
  Qed.

  Definition eqsemi_trans : Transitive eqSemiR.
    unfold Transitive.
    do 3 intro_destruct; crush_monoid.
  Qed.

  Global Add Parametric Relation : (G ⋉ A) eqSemiR
         reflexivity proved by eqsemi_refl
         symmetry proved by eqsemi_sym
         transitivity proved by eqsemi_trans as semiR_equiv.

  #[global] Instance rsemi_direct_product : BinOp (G ⋉ A) :=
    fun s1 s2 => match s1, s2 with
              | semiR g1 a1, semiR g2 a2 => semiR (g1 ** g2) (a1 ** g1 • a2)
              end.

  #[global] Instance semiRSetoid : Setoid (G ⋉ A) :=
    {| SetoidClass.equiv := eqSemiR |}.

  Global Add Parametric Morphism : binop with signature
         SetoidClass.equiv ==>
                           SetoidClass.equiv  ==> SetoidClass.equiv
           as rsemi_direct_product_mor.
  crush_morph 2.
  Qed.

  #[global] Program Instance semiR_monoid : Monoid (G ⋉ A) :=
    {| ε := semiR ε ε;
      left_identity := _;
      right_identity := _;
      associativity := _;
    |}.

  Next Obligation.
    destruct x as [g a];
      simpl; crush_monoid;
      rewrite (lact_trivial a); crush_monoid.
  Qed.

  Next Obligation.
    destruct x as [g a]; simpl;
      crush_monoid;
      rewrite (lact_unit g); crush_monoid.
  Qed.

  Next Obligation.
    destruct x as [g a];
      destruct y as [h b];
      destruct z as [k c]; simpl.
    crush_monoid.
    rewrite (lact_compose g h c).
    rewrite (lact_preserve_product g b (h•c)).
    crush_monoid.
  Qed.

End SemiDirectProduct.

(** **

This marks the separator between definitions that should not be using
the eq_setoid and those that 'can'.

 *)

#[global] Instance eq_setoid T : Setoid T | 10
  := { equiv := eq }.

#[global] Instance list_append_binop (A : Type) : BinOp (list A) := List.app (A :=A).

#[global] Instance list_is_monoid (A : Type)
  : Monoid (list A) := {| ε  := nil;
                          left_identity  := app_nil_l (A:=A);
                          right_identity := app_nil_r (A:=A);
                          associativity  := app_assoc (A:=A)
                       |}.

#[global] Instance transition_binop (A : Type) : BinOp (A -> A) :=  fun (f g : A -> A) => compose g f.
#[global] Instance transition_setoid (A : Type) : Setoid (A -> A) :=
  {| SetoidClass.equiv := eq |}.
Add Parametric Morphism A : binop with signature
    SetoidClass.equiv (A:= A -> A)==> SetoidClass.equiv  ==> SetoidClass.equiv
      as transition_mor.
  crush_monoid.
Qed.

#[global] Program Instance transition_monoid (A : Type) : Monoid (A -> A) :=
  {| ε := @id A |}.

#[global] Instance prop_prod : BinOp Prop := and.
#[global] Program Instance prop_monoid : Monoid Prop :=
  {| ε := True |}.
Next Obligation.
  unfold binop; unfold prop_prod. intuition.
Qed.

Next Obligation.
  unfold binop; unfold prop_prod. intuition.
Qed.

Next Obligation.
  unfold binop; unfold prop_prod. intuition.
Qed.

(* The following definitions are towards giving a monoid structure for
   the Abstract Machine.

   Code there is of the type

   (state -> state) * (state * state -> Prop)

   to capture both the state transition and annotations on the state.
 *)

(*
Definition comp A B `{Monoid B} : action (A -> A) (A -> B).
  refine (existT _ twist
                 {|
                   well_def := _;
                   unit_map := _;
                   commute  := _
                 |}).
unfold twist.
simpl.
unfold End.eq.
simpl.
intros.
unfold ">->".
now rewrite H1.

easy.
easy.
Defined.

Definition halfcomp A B `{Monoid B} : action (A -> A) (A*A -> B).

  refine (existT _ halftwist
                 {|
                   well_def := _;
                   unit_map := _;
                   commute  := _
                 |}).

simpl.
unfold halftwist.
unfold End.eq.
simpl.
unfold ">->".
intros.
now rewrite H1.

simpl.
unfold End.eq.
unfold halftwist.
simpl.
unfold id.
unfold compose.
intros.
now rewrite <- (surjective_pairing).

now unfold halftwist.

Defined.

#[global] Instance sdp_halfcomp A B `{Monoid B} : Monoid ((A -> A)*(A*A -> B))
  := semi_direct_prod _ _ (halfcomp A B).
*)

Require List.
Import List.ListNotations.

Goal [1 ; 2] ** [2 ; 3] = [1 ; 2 ; 2 ; 3].
  trivial.
Qed.

Goal ([1] , [1]) ** ([2] , [2]) = ([1 ; 2] , [1; 2]).
  trivial.
Qed.

Goal {- [1] -} ** error I = error I.
  trivial.
Qed.


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

Arguments nil {X}.
Arguments cons {X}.

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

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

(* Prior proven theorems/lemmas *)
Theorem app_assoc : forall A (l m n:list A),
  l ++ m ++ n = (l ++ m) ++ n.
Proof.
    intros A l m n. induction l as [| k l' IHl'].
    - simpl. reflexivity.
    - simpl. rewrite -> IHl'. reflexivity.
    Qed.

(* additional lemmas *)
Lemma list_app_nil : forall X (l1 : list X),
    l1 ++ [] = l1.
Proof.
    intros X l1. induction l1 as [| n l1' IHl1'].
    - simpl. reflexivity.
    - simpl. rewrite -> IHl1'. reflexivity.
    Qed.

(* exercise *)
Theorem rev_app_distr: forall X (l1 l2 : list X),
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
    intros X l1 l2. induction l1 as [| n l1' IHl'].
    - simpl. rewrite -> list_app_nil. reflexivity.
    - simpl. rewrite -> IHl'. rewrite -> app_assoc. reflexivity.
    Qed.

(* exercise *)
Theorem rev_involutive : forall X : Type, forall l : list X,
  rev (rev l) = l.
Proof.
    intros X l. induction l as [| n l' IHl'].
    - simpl. reflexivity.
    - simpl. rewrite -> rev_app_distr. rewrite -> IHl'. simpl. reflexivity.
    Qed.


(* "especially useful" *)

Inductive natlist : Type :=
  | nil
  | cons (n : nat) (l : 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).

(* A bag (or multiset) is like a set, except that each element can appear multiple times rather than just once. One possible representation for a bag of numbers is as a list. *)
Definition bag := natlist.

Fixpoint eqb (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' => eqb n' m'
            end
  end.

Fixpoint count (v : nat) (s : bag) : nat :=
    match s with
    | nil => O
    | h :: t => match eqb v h with
        | true => 1 + count v t
        | false => count v t
        end
    end.

Example test_count1: count 1 [1;2;3;1;4;1] = 3.
Proof. reflexivity. Qed.

Example test_count2: count 6 [1;2;3;1;4;1] = 0.
Proof. reflexivity. Qed.

Definition sum : bag -> bag -> bag := app.

Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.
Proof. simpl. reflexivity. Qed.

Definition add (v : nat) (s : bag) : bag :=
  sum [v] s.

Example test_add1: count 1 (add 1 [1;4;1]) = 3.
Proof. simpl. reflexivity. Qed.
Example test_add2: count 5 (add 1 [1;4;1]) = 0.
Proof. simpl. reflexivity. Qed.

Fixpoint member (v : nat) (s : bag) : bool :=
  match s with
  | nil => false
  | h :: t => match eqb h v with
    | true => true
    | false => member v t
    end
  end.

Example test_member1: member 1 [1;4;1] = true.
Proof. simpl. reflexivity. Qed.

Example test_member2: member 2 [1;4;1] = false.
Proof. simpl. reflexivity. Qed.


(** This file was originally written by Niels van der Weide and Dan Frumin.  *)
Require Import HoTT.
From GCTT Require Export basics.heterogeneous_equality basics.path_over.

(** Squares represents heterogeneous equalities between paths.
    A square has 4 sides `t`, `l`, `r`, `d` and it represents `l^ @ t @ r = d`.
    One way to define it, is using an inductive type with one constructor.
 *)
Inductive square {A : Type} :
  forall {lt rt ld rd : A}
         (t : lt = rt)
         (l : ld = lt) (r : rd = rt)
         (d : ld = rd),
    Type
  := id_square : forall {a : A},
      square (@idpath _ a) idpath idpath (@idpath _ a).

(** We can also use another constructor. *)
Inductive square_lr  {A : Type} :
  forall {lt rt ld rd : A}
         (t : lt = rt)
         (l : ld = lt) (r : rd = rt)
         (d : ld = rd),
    Type
  := id_square_lr : forall {t d : A}
                           {l : d = t} {r : d = t}
                           (h : l = r),
      square_lr idpath l r idpath.

Section equivalences.
  (** An equivalent definition of `square t l r d` is `l @ t = d @ r`.
      So, it is equivalent to a homotopy.
   *)
  Definition square_to_path
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (s : square t l r d)
    : l @ t = d @ r
    := match s with
       | id_square a => idpath
       end.

  Definition path_to_square
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (p : l @ t = d @ r)
    : square t l r d.
  Proof.
    induction t, l, d.
    exact (transport
             (fun z => square 1 1 z 1)
             (cancelL idpath idpath r p)
             id_square).
  Defined.

  Global Instance square_to_path_is_equiv
         {A : Type}
         {lt rt ld rd : A}
         {t : lt = rt}
         {l : ld = lt} {r : rd = rt}
         {d : ld = rd}
    : IsEquiv (@square_to_path _ _ _ _ _ t l r d).
  Proof.
    simple refine (isequiv_adjointify _ path_to_square _ _).
    - intros p.
      induction t, l, d ; cbn.
      refine (_ @ @eissect _ _ (cancelL 1 1 r) (isequiv_cancelL _ _ _) _).
      induction (cancelL idpath idpath r p) ; cbn.
      reflexivity.
    - intros x.
      induction x ; reflexivity.
  Defined.

  (** The two inductive definitions of squares are equivalent. *)
  Definition square_to_square_lr
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (s : square t l r d)
    : square_lr t l r d
    := match s with
       | id_square _ => id_square_lr idpath
       end.

  Definition square_lr_to_square
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (s : square_lr t l r d)
    : square t l r d.
  Proof.
    induction s, l.
    exact (transport
             (fun z => square idpath idpath z idpath)
             h
             id_square).
  Defined.

  Global Instance square_to_square_lr_isequiv
         {A : Type}
         {lt rt ld rd : A}
         {t : lt = rt}
         {l : ld = lt} {r : rd = rt}
         {d : ld = rd}
    : IsEquiv (@square_to_square_lr _ _ _ _ _ t l r d).
  Proof.
    simple refine (isequiv_adjointify _ square_lr_to_square _ _).
    - intros x.
      induction x, l, h ; reflexivity.
    - intros x ; induction x.
      reflexivity.
  Defined.

  (** A square is a path over a pair of paths in a family of paths. *)
  Definition square_to_path_over
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (s : square t l r d)
    : path_over (fun (x : A * A) => fst x = snd x) (path_prod' d t) l r
    := match s with
       | id_square a => path_over_id _
       end.

  Definition path_over_to_square
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (q : path_over (fun (x : A * A) => fst x = snd x) (path_prod' d t) l r)
    : square t l r d.
  Proof.
    induction t, l, d.
    exact (transport
             (fun z => square idpath idpath z idpath)
             (path_over_to_path q)
             id_square).
  Defined.

  Global Instance square_to_path_over_is_equiv
         {A : Type}
         {lt rt ld rd : A}
         {t : lt = rt}
         {l : ld = lt} {r : rd = rt}
         {d : ld = rd}
    : IsEquiv (@square_to_path_over A lt rt ld rd t l r d).
  Proof.
    simple refine (isequiv_adjointify _ (@path_over_to_square A _ _ _ _ t l r d) _ _).
    - intros x ; induction t, l, d ; cbn in *.
      refine (_ @ eissect path_over_to_path x).
      induction (path_over_to_path x).
      reflexivity.
    - intros x ; induction x.
      reflexivity.
  Defined.
End equivalences.

Section operations.
  (** We have two identity paths.
      The first one is between the top and bottom side.
   *)
  Definition hrefl
             {A : Type} {a b : A}
             (p : a = b)
    : square p idpath idpath p
    := match p with
       | idpath => id_square
       end.

  (** The second identity is between the left and right side. *)
  Definition vrefl
             {A : Type} {a b : A}
             (p : a = b)
    : square idpath p p idpath
    := match p with
       | idpath => id_square
       end.

  (** We can apply maps to squares. *)
  Definition ap_square
             {A B : Type} (f : A -> B)
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (s : square t l r d)
    : square (ap f t) (ap f l) (ap f r) (ap f d)
    := match s with
       | id_square _ => id_square
       end.

  (** We can make squares of pairs. *)
  Definition pair_square
             {A B : Type}
             {lta rta lda rda : A}
             {ta : lta = rta}
             {la : lda = lta} {ra : rda = rta}
             {da : lda = rda}
             {ltb rtb ldb rdb : B}
             {tb : ltb = rtb}
             {lb : ldb = ltb} {rb : rdb = rtb}
             {db : ldb = rdb}
             (sa : square ta la ra da)
             (sb : square tb lb rb db)
    : square (path_prod' ta tb)
             (path_prod' la lb)
             (path_prod' ra rb)
             (path_prod' da db)
    := match sa, sb with
       | id_square _, id_square _ => id_square
       end.

  (** We can move a square along paths in each coordinate. *)
  Definition whisker_square
             {A : Type}
             {lt rt ld rd : A}
             {t₁ t₂ : lt = rt}
             {l₁ l₂ : ld = lt} {r₁ r₂ : rd = rt}
             {d₁ d₂ : ld = rd}
             (pt : t₁ = t₂)
             (pl : l₁ = l₂) (pr : r₁ = r₂)
             (pd : d₁ = d₂)
             (s : square t₁ l₁ r₁ d₁)
    : square t₂ l₂ r₂ d₂.
  Proof.
    induction s.
    refine (transport (square t₂ l₂ r₂) pd _).
    refine (transport (fun z => square t₂ l₂ z _) pr _).
    refine (transport (fun z => square t₂ z _ _) pl _).
    exact (transport (fun z => square z _ _ _) pt id_square).
  Defined.

  (** Vertical composition of squares. *)
  Definition compose_square_v
             {A : Type}
             {lt rt : A}
             {lm rm : A}
             {ld rd : A}
             {t : lt = rt}
             {l₁ : lm = lt} {r₁ : rm = rt}
             {m : lm = rm}
             {l₂ : ld = lm} {r₂ : rd = rm}
             {d : ld = rd}
             (s₁ : square t l₁ r₁ m)
             (s₂ : square m l₂ r₂ d)
    : square t (l₂ @ l₁) (r₂ @ r₁) d.
  Proof.
    induction s₁.
    exact (whisker_square
             idpath
             (concat_p1 l₂)^
             (concat_p1 r₂)^
             idpath
             s₂).
  Defined.

  (** Horizontal composition of squares. *)
  Definition compose_square_h
             {A : Type}
             {lt mt rt : A}
             {ld md rd : A}
             {t₁ : lt = mt} {t₂ : mt = rt}
             {l : ld = lt} {m : md = mt} {r : rd = rt}
             {d₁ : ld = md} {d₂ : md = rd}
             (s₁ : square t₁ l m d₁)
             (s₂ : square t₂ m r d₂)
    : square (t₁ @ t₂) l r (d₁ @ d₂).
  Proof.
    induction s₁.
    exact (whisker_square
             ((concat_1p t₂)^)
             idpath
             idpath
             ((concat_1p d₂)^)
             s₂).
  Defined.

  (** We can rotate squares.
      This gives an equivalence.
   *)
  Definition square_symmetry
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
             (s : square t l r d)
    : square r d t l
    := match s with
       | id_square _ => id_square
       end.

  Global Instance square_symmetry_isequiv
         {A : Type}
         {lt rt ld rd : A}
         {t : lt = rt}
         {l : ld = lt} {r : rd = rt}
         {d : ld = rd}
    : IsEquiv (@square_symmetry A lt rt ld rd t l r d).
  Proof.
    simple refine (isequiv_adjointify _ square_symmetry _ _) ;
      intro x ; induction x ; reflexivity.
  Defined.

  (** If one side of the square is missing, then we can fill it.
      This is a Kan-filling.
   *)
  Definition fill_square_top
             {A : Type}
             {lt rt ld rd : A}
             {l : ld = lt} {r : rd = rt}
             {d : ld = rd}
    : {t : lt = rt & square t l r d}
    := (l^ @ d @ r;
          path_to_square ((concat_p_pp _ _ _)
                            @ (ap (fun z => z @ _) (concat_p_pp _ _ _))
                            @ (ap (fun z => (z @ _) @ _) (concat_pV l))
                            @ (ap (fun z => z @ _) (concat_1p _)))).

  Definition fill_square_left
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {r : rd = rt}
             {d : ld = rd}
    : {l : ld = lt & square t l r d}
    := (d @ r @ t^;
          path_to_square ((ap (fun z => z @ _) (concat_pp_p _ _ _))
                            @ (concat_pp_p _ _ _)
                            @ (ap (fun z => _ @ z) (concat_pp_p _ _ _))
                            @ (ap (fun z => _ @ (_ @ z)) (concat_Vp _))
                            @ (ap (fun z => _ @ z) (concat_p1 _)))).

  Definition fill_square_right
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt}
             {d : ld = rd}
    : {r : rd = rt & square t l r d}
    := (d^ @ l @ t;
          path_to_square ((ap (fun z => z @ _) (concat_1p _)^)
                            @ (ap (fun z => (z @ _) @ _) (concat_pV _)^)
                            @ (ap (fun z => z @ _) (concat_p_pp _ _ _)^)
                            @ (concat_p_pp _ _ _)^)).

  Definition fill_square_down
             {A : Type}
             {lt rt ld rd : A}
             {t : lt = rt}
             {l : ld = lt} {r : rd = rt}
    : {d : ld = rd & square t l r d}
    := (l @ t @ r^;
          path_to_square ((ap (fun z => _ @ z) (concat_p1 _)^)
                            @ (ap (fun z => (_ @ (_ @ z))) (concat_Vp _)^)
                            @ (ap (fun z => _ @ z) (concat_pp_p _ _ _)^)
                            @ ((concat_pp_p _ _ _)^)
                            @ (ap (fun z => z @ _) (concat_pp_p _ _ _)^))).

  (** Next we want look at squares of the form `square t (ap f p) (ap g p) d`.
      These are the same as paths over `p` in the family `f z = g z.
      For that, we first need some lemmata.
   *)
  Definition path_to_transport
             {A B : Type} {f g : A -> B}
             {a₁ a₂ : A} {p : a₁ = a₂}
    : forall {l : f a₁ = g a₁} {r : f a₂ = g a₂} (q : ap f p @ r = l @ ap g p),
      transport (fun z : A => f z = g z) p l = r
    := match p with
       | idpath => fun l r q => (concat_p1 l)^ @ q^ @ concat_1p r
       end.

  Definition transport_to_path
             {A B : Type} {f g : A -> B}
             {a₁ a₂ : A} {p : a₁ = a₂}
    : forall {l : f a₁ = g a₁} {r : f a₂ = g a₂}
             (q : transport (fun z : A => f z = g z) p l = r),
      ap f p @ r = l @ ap g p
    := match p with
       | idpath => fun l r q => concat_1p r @ q^ @ (concat_p1 l)^
       end.

  Global Instance path_to_transport_is_equiv
         {A B : Type} {f g : A -> B}
         {a₁ a₂ : A} {p : a₁ = a₂}
         {l : f a₁ = g a₁} {r : f a₂ = g a₂}
    : IsEquiv (@path_to_transport A B f g a₁ a₂ p l r).
  Proof.
    simple refine (isequiv_adjointify _ transport_to_path _ _).
    - intros x.
      induction x, p ; cbn.
      rewrite !inv_pp, inv_V ; cbn.
      hott_simpl.
    - intros x.
      induction p ; cbn in * ; induction l ; cbn in *.
      rewrite !inv_pp, !inv_V ; cbn.
      hott_simpl.
  Defined.

  (** `path_over` in a family of equations is the same as giving a square. *)
  Definition map_path_over
             {A B : Type} {f g : A -> B}
             {a₁ a₂ : A} {p : a₁ = a₂}
             {l : f a₁ = g a₁} {r : f a₂ = g a₂}
    : square r (ap f p) (ap g p) l -> path_over (fun z => f z = g z) p l r
    := path_over_to_path^-1 o path_to_transport o square_to_path.

  Global Instance path_over_map_isequiv
         {A B : Type} {f g : A -> B}
         {a₁ a₂ : A} {p : a₁ = a₂}
         {l : f a₁ = g a₁} {r : f a₂ = g a₂}
    : IsEquiv (@map_path_over A B f g a₁ a₂ p l r).
  Proof.
    unfold map_path_over.
    apply isequiv_compose.
  Defined.
End operations.

(** `path_over` in a family of equations between dependent maps is the same as a square. *)
Definition map_path_over_D
           {A : Type}
           {Y : A -> Type}
           (f g : forall (a : A), Y a)
           {a₁ a₂ : A}
           (p : a₁ = a₂)
           (c₁ : f a₁ = g a₁) (c₂ : f a₂ = g a₂)
           (s : square c₂ (apD f p) (apD g p) (ap (transport Y p) c₁))
  : path_over (fun a => f a = g a) p c₁ c₂.
Proof.
  induction p.
  apply path_to_path_over ; simpl in *.
  exact ((concat_1p _)^ @ square_to_path s @ concat_p1 _ @ ap_idmap _)^.
Defined.


From mathcomp Require Import ssreflect ssrbool eqtype ssrnat ssralg ssrnum ssrint.

Import GRing.
Open Scope ring_scope.

Definition IMO1_problem (f: int -> int) := forall a b: int,
    (f(a * 2%:R) + f(b) * 2%:R = f(f(a + b))).

Definition IMO1_solution (f: int -> int) :=
  (exists t : int, forall x, f(x) = (x * 2%:R + t))
  \/ (forall x, f(x) = 0).

Theorem IMO1_complete (f: int -> int): IMO1_problem f -> IMO1_solution f.
Proof.
  move=> H.
  have H1 : (forall a : int, f(a*2%:R) + f(0) = f(a)*2%:R).
    move=> a; apply/eqP; rewrite eq_sym -subr_eq -(addrKA (f 0)) subr_eq -mulr2n.
    by rewrite -[f 0 *+ _]mulr_natr -{1}addrC -(mul0r 2%:R) !H add0r mul0r addr0.
  have H2 : (forall a b c d : int, a + b = c + d -> f(a) + f(b) = f(c) + f(d)).
  move=> a b c d abcd_eq; apply: (@mulrIz int_numDomainType 2%:R); first by [].
  rewrite -![2%:R *~ _]mulrzl !intz !mulrDl -[f(a)*_]H1 -[f(c)*_]H1 -![_ + f 0]addrC.
  by rewrite -!addrA; congr(_ + _); rewrite !H abcd_eq.
  have H3 : (forall a : int, f(a) = (f(1) - f(0))*a + f(0)).
  elim/int_ind => [| n IHn| n IHn]; first by rewrite mulr0 add0r.
  rewrite !intS; have H4 : f(0) + f(n.+1) = f(1) + f(n) by apply H2.
  rewrite -(addr0 (f (1 + n%:Z))) -{1}(subrr (f 0)) addrA [_ + f 0]addrC H4 IHn.
  rewrite !mulrDl !mulrDr !mulr1 -(addrA (f 1 * n)) (addrA (f 1)).
  rewrite -2?(addrA (f 1 + f 1 * n)); congr(_ + _); by rewrite addrC addrA.
  rewrite !intS; have H5 : f(1) + f(-(1 + n%:Z)) = f(0) + f(-n%:Z).
    by apply H2; rewrite -{1}(add0r 1) addrKA.
  rewrite -(addr0 (f (-(1 + n%:Z)))) -{1}(subrr (f 1)) addrA [_ + f 1]addrC H5 IHn.
  rewrite !mulrDl addrA addrC (addrC (f 0)) 3?addrA -{1}(mulr1 (f 1)) -mulrN.
  rewrite -{2 3 5}(mulr1 (f 0)) !mulrNN -2?addrA -[in RHS]addrA; congr(_ + _).
    by rewrite -mulrDr; congr(_ * _); apply/eqP; rewrite -addr_eq0 (addrC 1) subrKA.
  rewrite -!mulrDr; congr(_ * _); by rewrite addrA (addrC n%:Z).
  move:(H 0 0); rewrite mul0r add0r [in f(f(_))]H3 mulrC -{1 5}(mul1r (f 0)) -!mulrDl.
  set f00 := (f 0 == 0); have H6 : ((f 0 == 0) = f00) by [].
  case: f00 H6 => /eqP; rewrite ?eqb_id ?eqbF_neg; move=> H6.
    move=> _; move: (H 0 1); rewrite [in f(f(_))]H3 H6 subr0 !add0r addr0.
    set f10 := (f 1 == 0); have H7 : ((f 1 == 0) = f10) by [].
    case: f10 H7 => /eqP; move=> H8.
      move=> _; right; move=> x; by rewrite H3 H6 H8 subr0 mul0r.
    move=> H9; have H10: f 1 = 2.
      apply: (@mulrIz int_numDomainType (f 1)); first by apply/eqP.
      by rewrite -![(f 1) *~ _]mulrzl !intz -H9 mulrC.
    left; exists 0; move=> x; by rewrite H3 H6 H10 subr0 !addr0 mulrC.
  move=> H11; left; exists (f 0); move=> x; rewrite H3 mulrC; congr((_ * _) + _).
  apply/eqP; rewrite -(addr0 (f 1 - f 0)) -{2}(subrr 1) addrA subr_eq eq_sym addrC.
  apply/eqP; apply: (@mulrIz int_numDomainType (f 0)) ; first by apply/eqP.
     by rewrite -![(f 0) *~ _]mulrzl !intz -H11 mulrC.
Qed.

Theorem IMO1_sound (f: int -> int): IMO1_solution f -> IMO1_problem f.
Proof.
  move=> [[t H] | H] a b; rewrite !H; last by rewrite mul0r.
  rewrite !mulrDl -!(addrA (a * 2 * 2)); congr(_ + _); by rewrite addrC.
Qed.