(** * Lists: Working with Structured Data *)

Require Import Le Lt Gt Decidable PeanoNat.
From LF Require Export Induction.
Module NatList.

(* ################################################################# *)
(** * Pairs of Numbers *)

(** In an [Inductive] type definition, each constructor can take
    any number of arguments -- none (as with [true] and [O]), one (as
    with [S]), or more than one (as with [nybble], and here): *)

Inductive natprod : Type :=
| pair (n1 n2 : nat).

(** This declaration can be read: "There is just one way to
    construct a pair of numbers: by applying the constructor [pair] to
    two arguments of type [nat]." *)

Check (pair 3 5).

(** Here are simple functions for extracting the first and
    second components of a pair. *)

Definition fst (p : natprod) : nat :=
  match p with
  | pair x y => x
  end.

Definition snd (p : natprod) : nat :=
  match p with
  | pair x y => y
  end.

Compute (fst (pair 3 5)).
(* ===> 3 *)

(** Since pairs will be used heavily, it is nice to be able to
    write them with the standard mathematical notation [(x,y)] instead
    of [pair x y].  We can tell Coq to allow this with a [Notation]
    declaration. *)

Notation "( x , y )" := (pair x y).

(** The new pair notation can be used both in expressions and in
    pattern matches. *)

Compute (fst (3,5)).

Definition fst' (p : natprod) : nat :=
  match p with
  | (x,y) => x
  end.

Definition snd' (p : natprod) : nat :=
  match p with
  | (x,y) => y
  end.

Definition swap_pair (p : natprod) : natprod :=
  match p with
  | (x,y) => (y,x)
  end.

(** Note that pattern-matching on a pair (with parentheses: [(x, y)])
    is not to be confused with the "multiple pattern" syntax
    (with no parentheses: [x, y]) that we have seen previously.

    The above examples illustrate pattern matching on a pair with
    elements [x] and [y], whereas [minus] below (taken from
    [Basics]) performs pattern matching on the values [n]
    and [m].

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

    The distinction is minor, but it is worth knowing that they
    are not the same. For instance, the following definitions are
    ill-formed:

        (* Can't match on a pair with multiple patterns: *)
        Definition bad_fst (p : natprod) : nat :=
          match p with
          | x, y => x
          end.

        (* Can't match on multiple values with pair patterns: *)
        Definition bad_minus (n m : nat) : nat :=
          match n, m with
          | (O   , _   ) => O
          | (S _ , O   ) => n
          | (S n', S m') => bad_minus n' m'
          end.
*)

(** Let's try to prove a few simple facts about pairs.

    If we state things in a slightly peculiar way, we can complete
    proofs with just reflexivity (and its built-in simplification): *)

Theorem surjective_pairing' : forall (n m : nat),
  (n,m) = (fst (n,m), snd (n,m)).
Proof.
  reflexivity.  Qed.

(** But [reflexivity] is not enough if we state the lemma in a more
    natural way: *)

Theorem surjective_pairing_stuck : forall (p : natprod),
  p = (fst p, snd p).
Proof.
  simpl. (* Doesn't reduce anything! *)
Abort.

(** We have to expose the structure of [p] so that [simpl] can
    perform the pattern match in [fst] and [snd].  We can do this with
    [destruct]. *)

Theorem surjective_pairing : forall (p : natprod),
  p = (fst p, snd p).
Proof.
  intros p.  destruct p as [n m].  simpl.  reflexivity.  Qed.

(** Notice that, unlike its behavior with [nat]s, where it
    generates two subgoals, [destruct] generates just one subgoal
    here.  That's because [natprod]s can only be constructed in one
    way. *)

(** **** Exercise: 1 star, standard (snd_fst_is_swap)  *)
Theorem snd_fst_is_swap : forall (p : natprod),
  (snd p, fst p) = swap_pair p.
Proof.
  destruct p as [x y].
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 1 star, standard, optional (fst_swap_is_snd)  *)
Theorem fst_swap_is_snd : forall (p : natprod),
  fst (swap_pair p) = snd p.
Proof.
  destruct p as [x y].
  reflexivity.
Qed.
(** [] *)

(* ################################################################# *)
(** * Lists of Numbers *)

(** Generalizing the definition of pairs, we can describe the
    type of _lists_ of numbers like this: "A list is either the empty
    list or else a pair of a number and another list." *)

Inductive natlist : Type :=
  | nil
  | cons (n : nat) (l : natlist).

(** For example, here is a three-element list: *)

Definition mylist := cons 1 (cons 2 (cons 3 nil)).

(** As with pairs, it is more convenient to write lists in
    familiar programming notation.  The following declarations
    allow us to use [::] as an infix [cons] operator and square
    brackets as an "outfix" notation for constructing lists. *)

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

(** It is not necessary to understand the details of these
    declarations, but here is roughly what's going on in case you are
    interested.  The [right associativity] annotation tells Coq how to
    parenthesize expressions involving multiple uses of [::] so that,
    for example, the next three declarations mean exactly the same
    thing: *)

Definition mylist1 := 1 :: (2 :: (3 :: nil)).
Definition mylist2 := 1 :: 2 :: 3 :: nil.
Definition mylist3 := [1;2;3].

(** The [at level 60] part tells Coq how to parenthesize
    expressions that involve both [::] and some other infix operator.
    For example, since we defined [+] as infix notation for the [plus]
    function at level 50,

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

    the [+] operator will bind tighter than [::], so [1 + 2 :: [3]]
    will be parsed, as we'd expect, as [(1 + 2) :: [3]] rather than
    [1 + (2 :: [3])].

    (Expressions like "[1 + 2 :: [3]]" can be a little confusing when
    you read them in a [.v] file.  The inner brackets, around 3, indicate
    a list, but the outer brackets, which are invisible in the HTML
    rendering, are there to instruct the "coqdoc" tool that the bracketed
    part should be displayed as Coq code rather than running text.)

    The second and third [Notation] declarations above introduce the
    standard square-bracket notation for lists; the right-hand side of
    the third one illustrates Coq's syntax for declaring n-ary
    notations and translating them to nested sequences of binary
    constructors. *)

(* ----------------------------------------------------------------- *)
(** *** Repeat *)

(** A number of functions are useful for manipulating lists.
    For example, the [repeat] function takes a number [n] and a
    [count] and returns a list of length [count] where every element
    is [n]. *)

Fixpoint repeat (n count : nat) : natlist :=
  match count with
  | O => nil
  | S count' => n :: (repeat n count')
  end.

(* ----------------------------------------------------------------- *)
(** *** Length *)

(** The [length] function calculates the length of a list. *)

Fixpoint length (l:natlist) : nat :=
  match l with
  | nil => O
  | h :: t => S (length t)
  end.

(* ----------------------------------------------------------------- *)
(** *** Append *)

(** The [app] function concatenates (appends) two lists. *)

Fixpoint app (l1 l2 : natlist) : natlist :=
  match l1 with
  | nil    => l2
  | h :: t => h :: (app t l2)
  end.

(** Since [app] will be used extensively in what follows, it is
    again convenient to have an infix operator for it. *)

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.

(* ----------------------------------------------------------------- *)
(** *** Head (With Default) and Tail *)

(** Here are two smaller examples of programming with lists.
    The [hd] function returns the first element (the "head") of the
    list, while [tl] returns everything but the first element (the
    "tail").  Since the empty list has no first element, we must pass
    a default value to be returned in that case.  *)

Definition hd (default:nat) (l:natlist) : nat :=
  match l with
  | nil => default
  | h :: t => h
  end.

Definition tl (l:natlist) : natlist :=
  match l with
  | nil => nil
  | h :: t => t
  end.

Example test_hd1:             hd 0 [1;2;3] = 1.
Proof. reflexivity.  Qed.
Example test_hd2:             hd 0 [] = 0.
Proof. reflexivity.  Qed.
Example test_tl:              tl [1;2;3] = [2;3].
Proof. reflexivity.  Qed.

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

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

    Complete the definitions of [nonzeros], [oddmembers], and
    [countoddmembers] below. Have a look at the tests to understand
    what these functions should do. *)

Fixpoint nonzeros (l:natlist) : natlist :=
  match l with
  | nil => nil
  | cons 0 l => (nonzeros l)
  | cons e l => cons e (nonzeros l)
  end.

Example test_nonzeros:
  nonzeros [0;1;0;2;3;0;0] = [1;2;3].
Proof. simpl. reflexivity. Qed.

Fixpoint oddmembers (l:natlist) : natlist :=
  match l with
  | nil => nil
  | cons e l =>
      match (evenb e) with
      | true => oddmembers l
      | false => cons e (oddmembers l)
      end
  end.

Example test_oddmembers:
  oddmembers [0;1;0;2;3;0;0] = [1;3].
Proof. simpl. reflexivity. Qed.

Fixpoint countoddmembers (l:natlist) : nat :=
  match l with
  | nil => O
  | cons e l =>
      match (evenb e) with
      | true => countoddmembers l
      | false => plus 1 (countoddmembers l)
      end
  end.

Example test_countoddmembers1:
  countoddmembers [1;0;3;1;4;5] = 4.
Proof. reflexivity. Qed.

Example test_countoddmembers2:
  countoddmembers [0;2;4] = 0.
Proof. reflexivity. Qed.

Example test_countoddmembers3:
  countoddmembers nil = 0.
Proof. reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (alternate)

    Complete the definition of [alternate], which interleaves two
    lists into one, alternating between elements taken from the first
    list and elements from the second.  See the tests below for more
    specific examples.

    (Note: one natural and elegant way of writing [alternate] will
    fail to satisfy Coq's requirement that all [Fixpoint] definitions
    be "obviously terminating."  If you find yourself in this rut,
    look for a slightly more verbose solution that considers elements
    of both lists at the same time.  One possible solution involves
    defining a new kind of pairs, but this is not the only way.)  *)

Fixpoint alternate (l1 l2 : natlist) : natlist :=
  match l1 with
  | nil => l2
  | cons e1 l1' =>
      match l2 with
      | nil => cons e1 l1'
      | cons e2 l2' => e1 :: e2 :: alternate l1' l2'
      end
  end.

Example test_alternate1:
  alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
Proof. reflexivity. Qed.

Example test_alternate2:
  alternate [1] [4;5;6] = [1;4;5;6].
Proof. reflexivity. Qed.

Example test_alternate3:
  alternate [1;2;3] [4] = [1;4;2;3].
Proof. reflexivity. Qed.

Example test_alternate4:
  alternate [] [20;30] = [20;30].
Proof. reflexivity. Qed.
(** [] *)

(* ----------------------------------------------------------------- *)
(** *** Bags via Lists *)

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

(** **** Exercise: 3 stars, standard, recommended (bag_functions)

    Complete the following definitions for the functions
    [count], [sum], [add], and [member] for bags. *)

Fixpoint count (v:nat) (s:bag) : nat :=
  match s with
  | nil => O
  | cons e l =>
      match (v =? e) with
      | true => 1 + count v l
      | false => count v l
      end
  end.

(** All these proofs can be done just by [reflexivity]. *)

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.

(** Multiset [sum] is similar to set [union]: [sum a b] contains all
    the elements of [a] and of [b].  (Mathematicians usually define
    [union] on multisets a little bit differently -- using max instead
    of sum -- which is why we don't use that name for this operation.)
    For [sum] we're giving you a header that does not give explicit
    names to the arguments.  Moreover, it uses the keyword
    [Definition] instead of [Fixpoint], so even if you had names for
    the arguments, you wouldn't be able to process them recursively.
    The point of stating the question this way is to encourage you to
    think about whether [sum] can be implemented in another way --
    perhaps by using functions that have already been defined.  *)

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

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

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

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

Definition member (v:nat) (s:bag) : bool := (notb ((count v s) =? 0)).

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

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

(** **** Exercise: 3 stars, standard, optional (bag_more_functions)

    Here are some more [bag] functions for you to practice with. *)

(** When [remove_one] is applied to a bag without the number to
    remove, it should return the same bag unchanged.  (This exercise
    is optional, but students following the advanced track will need
    to fill in the definition of [remove_one] for a later
    exercise.) *)

Fixpoint remove_one (v:nat) (s:bag) : bag :=
  match s with
  | nil => nil
  | cons e l =>
      match (v =? e) with
      | false => cons e (remove_one v l)
      | true => l
      end
  end.

Example test_remove_one1:
  count 5 (remove_one 5 [2;1;5;4;1]) = 0.
Proof. reflexivity. Qed.

Example test_remove_one2:
  count 5 (remove_one 5 [2;1;4;1]) = 0.
Proof. reflexivity. Qed.

Example test_remove_one3:
  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.
Proof. reflexivity. Qed.

Example test_remove_one4:
  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.
Proof. reflexivity. Qed.

Fixpoint remove_all (v:nat) (s:bag) : bag :=
  match s with
  | nil => nil
  | cons e l =>
      match (v =? e) with
      | false => cons e (remove_all v l)
      | true => remove_all v l
      end
  end.

Example test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.
Proof. reflexivity. Qed.
Example test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.
Proof. reflexivity. Qed.
Example test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.
Proof. reflexivity. Qed.
Example test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.
Proof. simpl. reflexivity. Qed.

Fixpoint subset (s1:bag) (s2:bag) : bool :=
  match s1 with
  | nil => true
  | cons e l =>
      match (member e s2) with
      | true => subset l (remove_one e s2)
      | false => false
      end
  end.

Example test_subset1:              subset [1;2] [2;1;4;1] = true.
Proof. reflexivity. Qed.
Example test_subset2:              subset [1;2;2] [2;1;4;1] = false.
Proof. reflexivity. Qed.
(** [] *)

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

    Write down an interesting theorem [bag_theorem] about bags
    involving the functions [count] and [add], and prove it.  Note
    that, since this problem is somewhat open-ended, it's possible
    that you may come up with a theorem which is true, but whose proof
    requires techniques you haven't learned yet.  Feel free to ask for
    help if you get stuck! *)

(*
Theorem bag_theorem : ...
Proof.
  ...
Qed.
*)

(* Do not modify the following line: *)
Definition manual_grade_for_bag_theorem : option (nat*string) := None.
(* Note to instructors: For silly technical reasons, in this
   file (only) you will need to write [Some (Datatypes.pair 3 ""%string)]
   rather than [Some (3,""%string)] to enter your grade and comments.

    [] *)

(* ################################################################# *)
(** * Reasoning About Lists *)

(** As for numbers, simple facts about list-processing functions
    can sometimes be proved entirely by simplification.  For example,
    the simplification performed by [reflexivity] is enough for this
    theorem... *)

Theorem nil_app : forall l:natlist,
  [] ++ l = l.
Proof. reflexivity. Qed.

(** ...because the [[]] is substituted into the
    "scrutinee" (the expression whose value is being "scrutinized" by
    the match) in the definition of [app], allowing the match itself
    to be simplified. *)

(** Also, as with numbers, it is sometimes helpful to perform case
    analysis on the possible shapes (empty or non-empty) of an unknown
    list. *)

Theorem tl_length_pred : forall l:natlist,
  pred (length l) = length (tl l).
Proof.
  intros l. destruct l as [| n l'].
  - (* l = nil *)
    reflexivity.
  - (* l = cons n l' *)
    reflexivity.  Qed.

(** Here, the [nil] case works because we've chosen to define
    [tl nil = nil]. Notice that the [as] annotation on the [destruct]
    tactic here introduces two names, [n] and [l'], corresponding to
    the fact that the [cons] constructor for lists takes two
    arguments (the head and tail of the list it is constructing). *)

(** Usually, though, interesting theorems about lists require
    induction for their proofs. *)

(* ----------------------------------------------------------------- *)
(** *** Micro-Sermon *)

(** Simply _reading_ proof scripts will not get you very far!  It is
    important to step through the details of each one using Coq and
    think about what each step achieves.  Otherwise it is more or less
    guaranteed that the exercises will make no sense when you get to
    them.  'Nuff said. *)

(* ================================================================= *)
(** ** Induction on Lists *)

(** Proofs by induction over datatypes like [natlist] are a
    little less familiar than standard natural number induction, but
    the idea is equally simple.  Each [Inductive] declaration defines
    a set of data values that can be built up using the declared
    constructors: a boolean can be either [true] or [false]; a number
    can be either [O] or [S] applied to another number; a list can be
    either [nil] or [cons] applied to a number and a list.

    Moreover, applications of the declared constructors to one another
    are the _only_ possible shapes that elements of an inductively
    defined set can have, and this fact directly gives rise to a way
    of reasoning about inductively defined sets: a number is either
    [O] or else it is [S] applied to some _smaller_ number; a list is
    either [nil] or else it is [cons] applied to some number and some
    _smaller_ list; etc. So, if we have in mind some proposition [P]
    that mentions a list [l] and we want to argue that [P] holds for
    _all_ lists, we can reason as follows:

      - First, show that [P] is true of [l] when [l] is [nil].

      - Then show that [P] is true of [l] when [l] is [cons n l'] for
        some number [n] and some smaller list [l'], assuming that [P]
        is true for [l'].

    Since larger lists can only be built up from smaller ones,
    eventually reaching [nil], these two arguments together establish
    the truth of [P] for all lists [l].  Here's a concrete example: *)

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

(** Notice that, as when doing induction on natural numbers, the
    [as...] clause provided to the [induction] tactic gives a name to
    the induction hypothesis corresponding to the smaller list [l1']
    in the [cons] case. Once again, this Coq proof is not especially
    illuminating as a static document -- it is easy to see what's
    going on if you are reading the proof in an interactive Coq
    session and you can see the current goal and context at each
    point, but this state is not visible in the written-down parts of
    the Coq proof.  So a natural-language proof -- one written for
    human readers -- will need to include more explicit signposts; in
    particular, it will help the reader stay oriented if we remind
    them exactly what the induction hypothesis is in the second
    case. *)

(** For comparison, here is an informal proof of the same theorem. *)

(** _Theorem_: For all lists [l1], [l2], and [l3],
   [(l1 ++ l2) ++ l3 = l1 ++ (l2 ++ l3)].

   _Proof_: By induction on [l1].

   - First, suppose [l1 = []].  We must show

       ([] ++ l2) ++ l3 = [] ++ (l2 ++ l3),

     which follows directly from the definition of [++].

   - Next, suppose [l1 = n::l1'], with

       (l1' ++ l2) ++ l3 = l1' ++ (l2 ++ l3)

     (the induction hypothesis). We must show

       ((n :: l1') ++ l2) ++ l3 = (n :: l1') ++ (l2 ++ l3).

     By the definition of [++], this follows from

       n :: ((l1' ++ l2) ++ l3) = n :: (l1' ++ (l2 ++ l3)),

     which is immediate from the induction hypothesis.  [] *)

(* ----------------------------------------------------------------- *)
(** *** Reversing a List *)

(** For a slightly more involved example of inductive proof over
    lists, suppose we use [app] to define a list-reversing function
    [rev]: *)

Fixpoint rev (l:natlist) : natlist :=
  match l with
  | nil    => nil
  | h :: t => rev t ++ [h]
  end.

Example test_rev1:            rev [1;2;3] = [3;2;1].
Proof. reflexivity.  Qed.
Example test_rev2:            rev nil = nil.
Proof. reflexivity.  Qed.

(* ----------------------------------------------------------------- *)
(** *** Properties of [rev] *)

(** Now, for something a bit more challenging than the proofs
    we've seen so far, let's prove that reversing a list does not
    change its length.  Our first attempt gets stuck in the successor
    case... *)

Theorem rev_length_firsttry : forall l : natlist,
  length (rev l) = length l.
Proof.
  intros l. induction l as [| n l' IHl'].
  - (* l = [] *)
    reflexivity.
  - (* l = n :: l' *)
    (* This is the tricky case.  Let's begin as usual
       by simplifying. *)
    simpl.
    (* Now we seem to be stuck: the goal is an equality
       involving [++], but we don't have any useful equations
       in either the immediate context or in the global
       environment!  We can make a little progress by using
       the IH to rewrite the goal... *)
    rewrite <- IHl'.
    (* ... but now we can't go any further. *)
Abort.

(** So let's take the equation relating [++] and [length] that
    would have enabled us to make progress and state it as a separate
    lemma. *)

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

(** Note that, to make the lemma as general as possible, we
    quantify over _all_ [natlist]s, not just those that result from an
    application of [rev].  This should seem natural, because the truth
    of the goal clearly doesn't depend on the list having been
    reversed.  Moreover, it is easier to prove the more general
    property. *)

(** Now we can complete the original proof. *)

Theorem rev_length : forall l : natlist,
  length (rev l) = length l.
Proof.
  intros l. induction l as [| n l' IHl'].
  - (* l = nil *)
    reflexivity.
  - (* l = cons *)
    simpl. rewrite -> app_length, plus_comm.
    simpl. rewrite -> IHl'. reflexivity.  Qed.

(** For comparison, here are informal proofs of these two theorems:

    _Theorem_: For all lists [l1] and [l2],
       [length (l1 ++ l2) = length l1 + length l2].

    _Proof_: By induction on [l1].

    - First, suppose [l1 = []].  We must show

        length ([] ++ l2) = length [] + length l2,

      which follows directly from the definitions of
      [length] and [++].

    - Next, suppose [l1 = n::l1'], with

        length (l1' ++ l2) = length l1' + length l2.

      We must show

        length ((n::l1') ++ l2) = length (n::l1') + length l2).

      This follows directly from the definitions of [length] and [++]
      together with the induction hypothesis. [] *)

(** _Theorem_: For all lists [l], [length (rev l) = length l].

    _Proof_: By induction on [l].

      - First, suppose [l = []].  We must show

          length (rev []) = length [],

        which follows directly from the definitions of [length]
        and [rev].

      - Next, suppose [l = n::l'], with

          length (rev l') = length l'.

        We must show

          length (rev (n :: l')) = length (n :: l').

        By the definition of [rev], this follows from

          length ((rev l') ++ [n]) = S (length l')

        which, by the previous lemma, is the same as

          length (rev l') + length [n] = S (length l').

        This follows directly from the induction hypothesis and the
        definition of [length]. [] *)

(** The style of these proofs is rather longwinded and pedantic.
    After the first few, we might find it easier to follow proofs that
    give fewer details (which we can easily work out in our own minds or
    on scratch paper if necessary) and just highlight the non-obvious
    steps.  In this more compressed style, the above proof might look
    like this: *)

(** _Theorem_:
     For all lists [l], [length (rev l) = length l].

    _Proof_: First, observe that [length (l ++ [n]) = S (length l)]
     for any [l] (this follows by a straightforward induction on [l]).
     The main property again follows by induction on [l], using the
     observation together with the induction hypothesis in the case
     where [l = n'::l']. [] *)

(** Which style is preferable in a given situation depends on
    the sophistication of the expected audience and how similar the
    proof at hand is to ones that the audience will already be
    familiar with.  The more pedantic style is a good default for our
    present purposes. *)

(* ================================================================= *)
(** ** [Search] *)

(** We've seen that proofs can make use of other theorems we've
    already proved, e.g., using [rewrite].  But in order to refer to a
    theorem, we need to know its name!  Indeed, it is often hard even
    to remember what theorems have been proven, much less what they
    are called.

    Coq's [Search] command is quite helpful with this.  Typing [Search
    foo] into your .v file and evaluating this line will cause Coq to
    display a list of all theorems involving [foo].  For example, try
    uncommenting the following line to see a list of theorems that we
    have proved about [rev]: *)

(*  Search rev. *)

(** Keep [Search] in mind as you do the following exercises and
    throughout the rest of the book; it can save you a lot of time!

    If you are using ProofGeneral, you can run [Search] with
    [C-c C-a C-a]. Pasting its response into your buffer can be
    accomplished with [C-c C-;]. *)

(* ================================================================= *)
(** ** List Exercises, Part 1 *)

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

    More practice with lists: *)

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

Theorem rev_app_distr: forall l1 l2 : natlist,
  rev (l1 ++ l2) = rev l2 ++ rev l1.
Proof.
  induction l1 as [|e1 l1' IHl1'].
  - simpl.
    intros l2.
    rewrite -> app_nil_r.
    reflexivity.
  - simpl.
    intros l2.
    rewrite -> IHl1', app_assoc.
    reflexivity.
Qed.

Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  induction l as [|e l' IHl'].
  - reflexivity.
  - simpl.
    rewrite -> rev_app_distr, IHl'.
    reflexivity.
Qed.

(** There is a short solution to the next one.  If you find yourself
    getting tangled up, step back and try to look for a simpler
    way. *)

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

(** An exercise about your implementation of [nonzeros]: *)

Check nonzeros.
Lemma nonzeros_app : forall l1 l2 : natlist,
  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).
Proof.
  induction l1 as [|e1 l1' IHl1'].
  - reflexivity.
  - simpl.
    intros l2.
    destruct e1.
    + rewrite -> IHl1'.
      reflexivity.
    + rewrite -> IHl1'.
      reflexivity.
Qed.
(** [] *)

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

    Fill in the definition of [eqblist], which compares
    lists of numbers for equality.  Prove that [eqblist l l]
    yields [true] for every list [l]. *)

Fixpoint eqblist (l1 l2 : natlist) : bool :=
  match l1 with
  | nil =>
      match l2 with
      | nil => true
      | cons e l => false
      end
  | cons e l =>
      match l2 with
      | nil => false
      | cons e' l' =>
          match (e =? e') with
          | true => eqblist l l'
          | false => false
          end
      end
  end.

Example test_eqblist1 :
  (eqblist nil nil = true).
Proof. reflexivity. Qed.

Example test_eqblist2 :
  eqblist [1;2;3] [1;2;3] = true.
Proof. reflexivity. Qed.

Example test_eqblist3 :
  eqblist [1;2;3] [1;2;4] = false.
Proof. reflexivity. Qed.

Theorem nat_eq_self:
  forall n:nat, (n =? n) = true.
Proof.
  induction n as [|n' IHn'].
  - reflexivity.
  - simpl.
    rewrite -> IHn'.
    reflexivity.
Qed.

Theorem eqblist_refl : forall l:natlist,
  true = eqblist l l.
Proof.
  induction l as [|e l' IHl'].
  - reflexivity.
  - simpl.
    rewrite <- IHl'.
    assert (H: forall n:nat, (n =? n) = true).
    { induction n as [|n' IHn'].
      - reflexivity.
      - simpl. rewrite -> IHn'. reflexivity. }
    rewrite -> H.
    reflexivity.
Qed.

(* ================================================================= *)
(** ** List Exercises, Part 2 *)

(** Here are a couple of little theorems to prove about your
    definitions about bags above. *)

(** **** Exercise: 1 star, standard (count_member_nonzero)  *)
Theorem count_member_nonzero : forall (s : bag),
  1 <=? (count 1 (1 :: s)) = true.
Proof.
  simpl.
  reflexivity.
Qed.
(** [] *)

(** The following lemma about [leb] might help you in the next exercise. *)

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

(** Before doing the next exercise, make sure you've filled in the
   definition of [remove_one] above. *)
(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count)  *)
Theorem remove_does_not_increase_count: forall (s : bag),
  (count 0 (remove_one 0 s)) <=? (count 0 s) = true.
Proof.
  induction s as [|e l' IHl'].
  - reflexivity.
  - simpl.
    destruct e.
    + simpl.
      rewrite -> leb_n_Sn.
      reflexivity.
    + simpl.
      rewrite -> IHl'.
      reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, standard, optional (bag_count_sum)

    Write down an interesting theorem [bag_count_sum] about bags
    involving the functions [count] and [sum], and prove it using
    Coq.  (You may find that the difficulty of the proof depends on
    how you defined [count]!) *)
Theorem count_and_sum:
  forall (n:nat) (l1 l2:bag),
    count n (sum l1 l2) = (count n l1) + (count n l2).
Proof.
  induction l1 as [|e1 l1' IHl1'].
  - simpl.
    reflexivity.
  - simpl.
    intros l2.
    rewrite -> IHl1'.
    destruct (n =? e1).
    + reflexivity.
    + reflexivity.
Qed.

(** **** Exercise: 4 stars, advanced (rev_injective)

    Prove that the [rev] function is injective -- that is,

    forall (l1 l2 : natlist), rev l1 = rev l2 -> l1 = l2.

    (There is a hard way and an easy way to do this.) *)

Theorem rev_injective':
  forall l1 l2:natlist, (rev l1 = rev l2) -> l1 = l2.
Proof.
  assert (H1: forall l1 l2:natlist, l1 = l2 -> (rev l1 = rev l2)).
  { intros l1 l2 H1'. rewrite -> H1'. reflexivity. }
  assert (H2: forall l1 l2:natlist, rev (rev l1) = rev (rev l2) -> l1 = l2).
  { intros l1 l2 H2'.
    rewrite -> rev_involutive in H2'.
    rewrite -> rev_involutive in H2'.
    rewrite -> H2'.
    reflexivity. }
  intros l1 l2 rev_eq_H.
  apply H1 in rev_eq_H as rev_rev_eq_H.
  apply H2 in rev_rev_eq_H as eq_H.
  apply eq_H.
Qed.

Theorem rev_injective:
  forall l1 l2:natlist, (rev l1 = rev l2) -> l1 = l2.
Proof.
  intros l1 l2 H.
  replace l1 with (rev (rev l1)).
  replace l2 with (rev (rev l2)).
  rewrite H.
  reflexivity.
  - rewrite -> rev_involutive.
    reflexivity.
  - rewrite -> rev_involutive.
    reflexivity.
Qed.

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

(* ################################################################# *)
(** * Options *)

(** Suppose we want to write a function that returns the [n]th
    element of some list.  If we give it type [nat -> natlist -> nat],
    then we'll have to choose some number to return when the list is
    too short... *)

Fixpoint nth_bad (l:natlist) (n:nat) : nat :=
  match l with
  | nil => 42  (* arbitrary! *)
  | a :: l' => match n =? O with
               | true => a
               | false => nth_bad l' (pred n)
               end
  end.

(** This solution is not so good: If [nth_bad] returns [42], we
    can't tell whether that value actually appears on the input
    without further processing. A better alternative is to change the
    return type of [nth_bad] to include an error value as a possible
    outcome. We call this type [natoption]. *)

Inductive natoption : Type :=
  | Some (n : nat)
  | None.

(** We can then change the above definition of [nth_bad] to
    return [None] when the list is too short and [Some a] when the
    list has enough members and [a] appears at position [n]. We call
    this new function [nth_error] to indicate that it may result in an
    error. *)

Fixpoint nth_error (l:natlist) (n:nat) : natoption :=
  match l with
  | nil => None
  | a :: l' => match n =? O with
               | true => Some a
               | false => nth_error l' (pred n)
               end
  end.

Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.
Proof. reflexivity. Qed.
Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.
Proof. reflexivity. Qed.
Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.
Proof. reflexivity. Qed.

(** (In the HTML version, the boilerplate proofs of these
    examples are elided.  Click on a box if you want to see one.)

    This example is also an opportunity to introduce one more small
    feature of Coq's programming language: conditional
    expressions... *)

Fixpoint nth_error' (l:natlist) (n:nat) : natoption :=
  match l with
  | nil => None
  | a :: l' => if n =? O then Some a
               else nth_error' l' (pred n)
  end.

(** Coq's conditionals are exactly like those found in any other
    language, with one small generalization.  Since the boolean type
    is not built in, Coq actually supports conditional expressions over
    _any_ inductively defined type with exactly two constructors.  The
    guard is considered true if it evaluates to the first constructor
    in the [Inductive] definition and false if it evaluates to the
    second. *)

(** The function below pulls the [nat] out of a [natoption], returning
    a supplied default in the [None] case. *)

Definition option_elim (d : nat) (o : natoption) : nat :=
  match o with
  | Some n' => n'
  | None => d
  end.

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

    Using the same idea, fix the [hd] function from earlier so we don't
    have to pass a default element for the [nil] case.  *)

Definition hd_error (l : natlist) : natoption :=
  match l with
  | nil => None
  | cons e l' => Some e
  end.

Example test_hd_error1 : hd_error [] = None.
Proof. trivial. Qed.

Example test_hd_error2 : hd_error [1] = Some 1.
Proof. trivial. Qed.

Example test_hd_error3 : hd_error [5;6] = Some 5.
Proof. trivial. Qed.
(** [] *)

(** **** Exercise: 1 star, standard, optional (option_elim_hd)

    This exercise relates your new [hd_error] to the old [hd]. *)

Theorem option_elim_hd : forall (l:natlist) (default:nat),
  hd default l = option_elim default (hd_error l).
Proof.
  induction l as [|e l' IHl'].
  - trivial.
  - trivial.
Qed.
(** [] *)

End NatList.

(* ################################################################# *)
(** * Partial Maps *)

(** As a final illustration of how data structures can be defined in
    Coq, here is a simple _partial map_ data type, analogous to the
    map or dictionary data structures found in most programming
    languages. *)

(** First, we define a new inductive datatype [id] to serve as the
    "keys" of our partial maps. *)

Inductive id : Type :=
  | Id (n : nat).

(** Internally, an [id] is just a number.  Introducing a separate type
    by wrapping each nat with the tag [Id] makes definitions more
    readable and gives us the flexibility to change representations
    later if we wish. *)

(** We'll also need an equality test for [id]s: *)

Definition eqb_id (x1 x2 : id) :=
  match x1, x2 with
  | Id n1, Id n2 => n1 =? n2
  end.

(** **** Exercise: 1 star, standard (eqb_id_refl)  *)
Theorem eqb_id_refl : forall x, true = eqb_id x x.
Proof.
  intros x.
  destruct x as [n].
  - simpl.
    rewrite -> (eqb_refl n).
    reflexivity.
Qed.
(** [] *)

(** Now we define the type of partial maps: *)

Module PartialMap.
Export NatList.

Inductive partial_map : Type :=
  | empty
  | record (i : id) (v : nat) (m : partial_map).

(** This declaration can be read: "There are two ways to construct a
    [partial_map]: either using the constructor [empty] to represent an
    empty partial map, or by applying the constructor [record] to
    a key, a value, and an existing [partial_map] to construct a
    [partial_map] with an additional key-to-value mapping." *)

(** The [update] function overrides the entry for a given key in a
    partial map by shadowing it with a new one (or simply adds a new
    entry if the given key is not already present). *)

Definition update (d : partial_map)
                  (x : id) (value : nat)
                  : partial_map :=
  record x value d.

(** Last, the [find] function searches a [partial_map] for a given
    key.  It returns [None] if the key was not found and [Some val] if
    the key was associated with [val]. If the same key is mapped to
    multiple values, [find] will return the first one it
    encounters. *)

Fixpoint find (x : id) (d : partial_map) : natoption :=
  match d with
  | empty         => None
  | record y v d' => if eqb_id x y
                     then Some v
                     else find x d'
  end.

(** **** Exercise: 1 star, standard (update_eq)  *)
Theorem update_eq :
  forall (d : partial_map) (x : id) (v: nat),
    find x (update d x v) = Some v.
Proof.
  intros d x v.
  simpl.
  rewrite <- (eqb_id_refl x).
  reflexivity.
Qed.
(** [] *)

(** **** Exercise: 1 star, standard (update_neq)  *)
Theorem update_neq :
  forall (d : partial_map) (x y : id) (o: nat),
    eqb_id x y = false -> find x (update d y o) = find x d.
Proof.
  intros.
  simpl.
  rewrite -> H.
  reflexivity.
Qed.
(** [] *)
End PartialMap.

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

    Consider the following inductive definition: *)

Inductive baz : Type :=
  | Baz1 (x : baz)
  | Baz2 (y : baz) (b : bool).

(** How _many_ elements does the type [baz] have? (Explain in words,
    in a comment.) *)

(* FILL IN HERE *)

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

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


(* ========================================================================== *]
 PROVING THINGS WE KNOW
[* ========================================================================== *)
Require Import Nat List Lia.

(* -------------------------------------------------------------------------- *]
 Let's prove things we consider true in our everyday programming life.

 We start by defining some common functions for lists.
[* -------------------------------------------------------------------------- *)

(* Calculate length of list. *)
Fixpoint length {A} (lst : list A) :=
    match lst with
    | nil => 0
    | x :: xs => 1 + length xs
    end.

(* Concatenate two lists. *)
Fixpoint concat {A} (lst1 lst2 : list A) :=
    match lst1 with
    | nil => lst2
    | x :: xs => x :: (concat xs lst2)
    end.

(* Reverse a list. *)
Fixpoint reverse {A} (lst : list A) :=
    match lst with
    | nil => nil
    | x :: xs => concat (reverse xs) (x :: nil)
    end.

(* Apply function on all elements of list. *)
Fixpoint map {A B} (f : A -> B) (lst : list A) :=
    match lst with
    | nil => nil
    | x :: xs => f x :: map f xs
    end.

(* Compose two functions into a single one. *)
Definition compose {A B C} (f : B -> C) (g : A -> B) :=
    fun x => f (g x).

(* -------------------------------------------------------------------------- *]
 Most often we need properties that describe how different functions interact.
[* -------------------------------------------------------------------------- *)

Lemma length_concat {A} (lst1 lst2 : list A):
    length (concat lst1 lst2) = length lst1 + length lst2.
Proof.
    induction lst1.
    - simpl. auto.
    - simpl. rewrite IHlst1. auto.
Qed.

Lemma length_map {A B} (lst : list A) (f : A -> B):
    length (map f lst) = length lst.
Proof.
    induction lst.
    - simpl. auto.
    - simpl. rewrite IHlst. auto.
Qed.

Lemma map_compose {A B C} (lst : list A) (f : B -> C) (g : A -> B):
    map f (map g lst) = map (compose f g) lst.
Proof.
    induction lst.
    - simpl. auto.
    - simpl. rewrite IHlst. unfold compose. auto.
Qed.

(* -------------------------------------------------------------------------- *]
 Sometimes we need to prove some auxiliary lemmas.
[* -------------------------------------------------------------------------- *)

(* These two seem obvious but must be shown. *)
Lemma concat_nil {A} (lst1 : list A):
    concat lst1 nil = lst1.
Proof.
    induction lst1.
    - simpl. auto.
    - simpl. rewrite IHlst1. auto.
Qed.

Lemma concat_assoc {A} (lst1 lst2 lst3 : list A):
    concat (concat lst1 lst2) lst3 = concat lst1 (concat lst2 lst3).
Proof.
    induction lst1.
    - simpl. auto.
    - simpl. rewrite IHlst1. auto.
Qed.

(* This is what we actually want. *)
Lemma reverse_concat {A} (lst1 lst2 : list A):
    reverse (concat lst1 lst2) = concat (reverse lst2) (reverse lst1).
Proof.
    induction lst1. simpl.
    - rewrite concat_nil. auto.
    - simpl. rewrite IHlst1. rewrite concat_assoc. auto.
Qed.

(* -------------------------------------------------------------------------- *]
 Induction needs to be performed at a general enough level in order to complete the following proof. If we try to first introduce all hypotheses, we get
 an induction hypothesis that is too weak.
[* -------------------------------------------------------------------------- *)

Fixpoint get_el {A} n (lst : list A) :=
    match lst, n with
    | nil, _ => None
    | x :: xs, 0 => Some x
    | x :: xs, S m => get_el m xs
    end.

Lemma get_fails {A} n (lst : list A) :
    length lst < n -> get_el n lst = None.
Proof.
    revert n.
    induction lst.
    - intros.
      destruct n.
        + simpl. auto.
        + simpl. auto.
    - intros.
      destruct n.
        + simpl. simpl in H. lia.
        + simpl. apply IHlst. simpl in H. lia.
Qed.

(* -------------------------------------------------------------------------- *]
 By defining an inductive data type, Coq already know precisely what the
 appropriate induction principle is.
[* -------------------------------------------------------------------------- *)

Inductive tree {A} :=
| Empty : tree
| Node : tree -> A -> tree -> tree
.

Fixpoint mirror {A} (t : @tree A) :=
    match t with
    | Empty => Empty
    | Node l_t x r_t => Node (mirror r_t) x (mirror l_t)
    end.

Fixpoint height {A} (t : @tree A) :=
    match t with
    | Empty => 0
    | Node l_t x r_t => 1 + max (height l_t) (height r_t)
    end.

Lemma height_mirror {A} (t : @tree A) :
    height (mirror t) = height t.
Proof.
    induction t.
    - simpl. auto.
    - simpl. rewrite IHt1, IHt2. lia.
Qed.

Lemma mirror_mirror {A} (t : @tree A) :
    mirror (mirror t) = t.
Proof.
    induction t.
    - simpl. auto.
    - simpl. rewrite IHt1, IHt2. auto.
Qed.


(* Chap 7 IndProp *)
Set Warnings "-notation-overridden,-parsing".
From LF Require Export Logic.
Require Coq.omega.Omega.

(* Chap 7.1 Inductively Defined Propositions *)
Inductive even: nat -> Prop :=
  | ev_0: even 0
  | ev_SS (n: nat) (H: even n) : even (S (S n)).

Inductive myeven: nat -> Prop :=
  | myev_0: myeven 0
  | myev_SS: forall n, myeven n -> myeven (S (S n)).

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

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

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

(* Exercise ev_double *)
Theorem ev_double: forall n,
  even (double n).
Proof.
  intros.
  induction n.
  - simpl. apply ev_0.
  - simpl. apply ev_SS, IHn.
Qed.

(* Chap 7.2 Using Evidence in Proofs *)
(* Chap 7.2.1 Inversion on Evidence *)
Theorem ev_inversion:
  forall n: nat, even n -> (n = 0) \/ (exists n', n = S (S n') /\ even n').
Proof.
  intros.
  destruct H.
  - left. reflexivity.
  - right. exists n.
    split.
    + reflexivity.
    + apply H.
Qed.

Theorem ev_minus2: forall n,
  even n -> even (pred (pred n)).
Proof.
  intros.
  destruct H.
  - simpl. apply ev_0.
  - simpl. apply H.
Qed.

Theorem evSS_ev: forall n,
  even (S (S n)) -> even n.
Proof.
  intros.
  apply ev_inversion in H.
  destruct H.
  - discriminate H.
  - destruct H as [n' [H1 H2]].
    injection H1 as H1.
    rewrite H1. apply H2.
Qed.

Theorem evSS_ev': forall n,
  even (S (S n)) -> even n.
Proof.
  intros.
  inversion H.
  apply H1.
Qed.

Theorem one_not_even: ~ even 1.
Proof.
  unfold not.
  intros.
  apply ev_inversion in H.
  destruct H.
  - discriminate H.
  - destruct H as [n' [H1 H2]].
    discriminate H1.
Qed.

(* Exercise inversion_practice *)
Theorem SSSSev__even: forall n,
  even (S (S (S (S n)))) -> even n.
Proof.
  intros.
  inversion H.
  inversion H1.
  apply H3.
Qed.

Theorem SSSSev__even': forall n,
  even (S (S (S (S n)))) -> even n.
Proof.
  intros.
  apply evSS_ev, evSS_ev, H.
Qed.

(* Theorem even5_nonsense *)
Theorem even5_nonsense:
  even 5 -> 2 + 2 = 9.
Proof.
  intros H.
  exfalso.
  inversion H.
  inversion H1.
  inversion H3.
Qed.

Theorem inversion_ex1: forall n m o: nat,
  [n; m] = [o; o] -> [n] = [m].
Proof.
  intros. inversion H. reflexivity.
Qed.

Theorem inversion_ex2: forall n: nat,
  S n = O -> 2 + 2 = 5.
Proof.
  intros. inversion H.
Qed.

(* Chap 7.2.2 Induction on Evidence *)
Lemma ev_even: forall n,
  even n -> exists k, n = double k.
Proof.
  intros.
  induction H.
  - exists 0. reflexivity.
  - destruct IHeven.
    rewrite H0.
    exists (S x).
    simpl. reflexivity.
Qed.

Theorem ev_sum: forall n m, even n -> even m -> even (n + m).
Proof.
  intros.
  induction H.
  - simpl. apply H0.
  - simpl. apply ev_SS, IHeven.
Qed.

Inductive even': nat -> Prop :=
  | even'_0: even' 0
  | even'_2: even' 2
  | even'_sum n m (Hn: even' n) (Hm: even' m): even' (n + m).

Theorem even'_ev: forall n, even' n <-> even n.
Proof.
  intros. split.
  - intros. induction H.
    + apply ev_0.
    + apply ev_SS, ev_0.
    + apply ev_sum. apply IHeven'1. apply IHeven'2.
  - intros. induction H.
    + apply even'_0.
    + assert (I: S (S n) = 2 + n).
      { simpl. reflexivity. }
      rewrite I. apply even'_sum.
      apply even'_2. apply IHeven.
Qed.

Theorem ev_ev__ev: forall n m,
  even (n+m) -> even n -> even m.
Proof.
  intros.
  induction H0.
  simpl in H.
  - apply H.
  - apply IHeven.
    simpl in H.
    apply evSS_ev in H.
    apply H.
Qed.

Lemma plus_twice_eq_double:
  forall n, n + n = double n.
Proof.
  intros.
  induction n.
  - reflexivity.
  - simpl. rewrite <- IHn.
    rewrite <- plus_n_Sm.
    reflexivity.
Qed.

Theorem ev_plus_plus: forall n m p,
  even (n+m) -> even (n+p) -> even (m+p).
Proof.
  intros.
  apply ev_ev__ev with (n := n + n).
  rewrite plus_assoc.
  assert(I: n + n + m = n + m + n).
  { rewrite <- plus_assoc. rewrite plus_comm. reflexivity. }
  rewrite I. rewrite <- plus_assoc.
  apply ev_sum.
  apply H.
  apply H0.
  rewrite plus_twice_eq_double.
  apply ev_double.
Qed.

(* Chap 7.3 Inductive Relations *)
Module Playground.

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

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

Theorem test_le1: 3 <= 3.
Proof. apply le_n. Qed.

Theorem test_le2: 3 <= 6.
Proof. apply le_S, le_S, le_S, le_n. Qed.

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

End Playground.

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

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

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

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

Inductive next_even: nat -> nat -> Prop :=
  | ne_1 n: even (S n) -> next_even n (S n)
  | ne_2 n (H: even (S (S n))): next_even n (S (S n)).

(* Exercise total_relation *)
Inductive total_relation: nat -> nat -> Prop :=
  | re_0_0: total_relation 0 0
  | re_S_0 n (H: total_relation n 0): total_relation (S n) 0
  | re_n_S n m (H: total_relation n m): total_relation n (S m).

(* Exercise empty_relation *)
Inductive empty_relation: nat -> nat -> Prop := .

(* Exercise le_exercises *)
Lemma le_trans: forall m n o, m <= n -> n <= o -> m <= o.
Proof.
  intros.
  induction H0.
  - apply H.
  - simpl. apply le_S, IHle.
Qed.

Theorem O_le_n: forall n, 0 <= n.
Proof.
  intros.
  induction n.
  - reflexivity.
  - apply le_S, IHn.
Qed.

Theorem n_le_m__Sn_le_Sm: forall n m, n <= m -> S n <= S m.
Proof.
  intros.
  induction H.
  - reflexivity.
  - apply le_S, IHle.
Qed.

Theorem Sn_le_Sm__n_le_m: forall n m, S n <= S m -> n <= m.
Proof.
  intros.
  inversion H.
  - apply le_n.
  - apply (le_trans n (S n)).
    + apply le_S, le_n.
    + apply H1.
Qed.

Theorem le_plus_l: forall a b, a <= a + b.
Proof.
  intros.
  induction b.
  - rewrite <- plus_n_O. apply le_n.
  - rewrite <- plus_n_Sm. apply le_S, IHb.
Qed.

Theorem plus_lt: forall n1 n2 m, n1 + n2 < m -> n1 < m /\ n2 < m.
Proof.
  unfold lt.
  intros.
  induction H.
  - split.
    + apply n_le_m__Sn_le_Sm, le_plus_l.
    + apply n_le_m__Sn_le_Sm.
      rewrite <- plus_comm.
      apply le_plus_l.
  - destruct IHle as [H1 H2].
    split.
    + apply le_S, H1.
    + apply le_S, H2.
Qed.

Theorem lt_S: forall n m, n < m -> n < S m.
Proof.
  unfold lt.
  intros.
  apply le_S, H.
Qed.

Theorem leb_complete: forall n m, n <=? m = true -> n <= m.
Proof.
  intros.
  generalize dependent n.
  induction m.
  - intros. induction n.
    + apply le_n.
    + inversion H.
  - intros. induction n.
    + apply O_le_n.
    + apply n_le_m__Sn_le_Sm, IHm, H.
Qed.

(* This is the version of induction n. *)
Theorem leb_correct: forall n m, n <= m -> n <=? m = true.
Proof.
  intros n.
  induction n.
  - intros. inversion H.
    + reflexivity.
    + reflexivity.
  - intros. inversion H.
    + simpl. rewrite <- leb_refl. reflexivity.
    + simpl. apply IHn. apply le_trans with (n := S n).
      apply le_S, le_n. apply H0.
Qed.

Theorem leb_true_trans: forall n m o,
  n <=? m = true -> m <=? o = true -> n <=? o = true.
Proof.
  intros.
  apply leb_correct.
  apply leb_complete in H.
  apply leb_complete in H0.
  apply le_trans with (n := m).
  apply H.
  apply H0.
Qed.
(* Ques: how to use "induction" to proof this? *)

(* Exercise leb_iff *)
Theorem leb_iff: forall n m, n <=? m = true <-> n <= m.
Proof.
  split.
  - apply leb_complete.
  - apply leb_correct.
Qed.

Module R.
(* Exercise R_provability, R_fact *)
Inductive R: nat -> nat -> nat -> Prop :=
   | c1: R 0 0 0
   | c2 m n o (H: R m n o): R (S m) n (S o)
   | c3 m n o (H: R m n o): R m (S n) (S o)
   | c4 m n o (H: R (S m) (S n) (S (S o))): R m n o
   | c5 m n o (H: R m n o): R n m o.

Definition fR: nat -> nat -> nat := plus.

Theorem R_equiv_fR: forall m n o, R m n o <-> fR m n = o.
Proof.
  intros. split.
  - intros. induction H.
    + reflexivity.
    + unfold fR. simpl.
      unfold fR in IHR.
      apply f_equal, IHR.
    + unfold fR. rewrite <- plus_n_Sm.
      unfold fR in IHR.
      apply f_equal, IHR.
    + unfold fR. unfold fR in IHR. simpl in IHR.
      injection IHR. intros.
      rewrite <- plus_n_Sm in H0.
      injection H0 as H0. apply H0.
    + unfold fR. unfold fR in IHR.
      rewrite plus_comm. apply IHR.
  - generalize dependent n.
    generalize dependent o.
    induction m.
    + intros n. induction n.
      * intros. simpl in H. rewrite H. apply c1.
      * intros. simpl in H. simpl in IHn. rewrite H. apply c3, IHn. reflexivity.
    + intros n. induction n.
      * intros. discriminate H.
      * intros. simpl in H. injection H as H. apply c2. apply IHm, H.
Qed.

End R.

(* Exercise subsequence *)
Inductive subseq {X: Type}: list X -> list X -> Prop :=
  | empty l: subseq [] l
  | remove_one x l1 l2 (H: subseq l1 l2): subseq l1 (x :: l2)
  | remove_both x l1 l2 (H: subseq l1 l2): subseq (x :: l1) (x :: l2).

Theorem subseq_refl: forall X (l: list X), subseq l l.
Proof.
  intros.
  induction l.
  - apply empty.
  - apply remove_both, IHl.
Qed.

Theorem subseq_app: forall X (l1 l2 l3: list X), subseq l1 l2 -> subseq l1 (l2 ++ l3).
Proof.
  intros.
  induction H.
  - apply empty.
  - simpl. apply remove_one, IHsubseq.
  - simpl. apply remove_both, IHsubseq.
Qed.

Lemma subset_empty_is_empty: forall X (l: list X), subseq l [] -> l = [].
Proof.
  intros.
  inversion H.
  reflexivity.
Qed.

Theorem subseq_trans: forall X (l1 l2 l3: list X), subseq l1 l2 -> subseq l2 l3 -> subseq l1 l3.
Proof.
  intros.
  generalize dependent l1.
  induction H0.
  - intros. apply subset_empty_is_empty in H.
    rewrite H. apply empty.
  - intros. apply remove_one, IHsubseq, H.
  - intros. inversion H.
    + apply empty.
    + apply remove_one, IHsubseq, H3.
    + apply remove_both, IHsubseq, H3.
Qed.

(* Exercise R_provability2 *)
Module Ex_R.

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.

Example R_ex1: R 2 [1; 0].
Proof. apply c2, c2, c1. Qed.

Example R_ex2: R 1 [1; 2; 1; 0].
Proof. apply c3, c2, c3, c3, c2, c2, c2, c1. Qed.

(* Example R_ex3: R 6 [3; 2; 1; 0]. This cannot be proved. *)

End Ex_R.

(* Chap 7.4 Case Study: Regular Expressions *)
Inductive reg_exp {T: Type} : Type :=
  | EmptySet
  | EmptyStr
  | Char (t: T)
  | App (r1 r2: reg_exp)
  | Union (r1 r2: reg_exp)
  | Star (r: reg_exp).

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

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

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] (Char 1) [2] (Char 2)).
  - apply MChar.
  - apply MChar.
Qed.

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

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.
  apply (MApp [1] _ [2; 3]).
  - apply MChar.
  - apply (MApp [2] _ [3]).
    + apply MChar.
    + apply (MApp [3] _ []).
      * apply MChar.
      * apply MEmpty.
Qed.

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

(* Example exp_match_ex1 *)
Lemma empty_is_empty: forall T (s: list T), ~(s =~ EmptySet).
Proof.
  unfold not. intros. 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. destruct H as [H1 | H2].
  - apply (MUnionL s re1 re2), H1.
  - apply (MUnionR s re1 re2), H2.
Qed.

Lemma MStar': forall T (ss: list (list T)) (re: reg_exp),
  (forall s, In s ss -> s =~ re) -> fold app ss [] =~ Star re.
Proof.
  intros. induction ss.
  - simpl. apply MStar0.
  - simpl. apply MStarApp.
    + apply H. simpl. left. reflexivity.
    + apply IHss. intros. apply H. simpl. right. apply H0.
Qed.

(* Exercise reg_exp_of_list_spec *)
Lemma reg_exp_of_list_spec: forall T (s1 s2: list T),
  s1 =~ reg_exp_of_list s2 <-> s1 = s2.
Proof.
  split.
  - generalize dependent s1.
    induction s2.
    + intros. simpl in H. inversion H. reflexivity.
    + intros. simpl in H. inversion H. apply IHs2 in H4.
      inversion H3. rewrite H4. simpl. reflexivity.
  - generalize dependent s2.
    induction s1.
    + intros. rewrite <- H. simpl. apply MEmpty.
    + intros. rewrite <- H. simpl.
      replace (x :: s1) with ([x] ++ s1).
      apply MApp.
      * apply MChar.
      * apply IHs1. reflexivity.
      * simpl. reflexivity.
Qed.

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.

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.
  induction H.
  - simpl in H0. simpl. apply H0.
  - simpl in H0. simpl. apply H0.
  - simpl. rewrite In_app_iff in *.
    destruct H0 as [H2 | H3].
    + left. apply IHexp_match1, H2.
    + right. apply IHexp_match2, H3.
  - simpl. rewrite In_app_iff.
    left. apply IHexp_match, H0.
  - simpl. rewrite In_app_iff.
    right. apply IHexp_match, H0.
  - destruct H0.
  - simpl in *. rewrite In_app_iff in *.
    destruct H0 as [H2 | H3].
    + apply IHexp_match1, H2.
    + apply IHexp_match2, H3.
Qed.

(* Exercise re_not_empty *)
Fixpoint re_not_empty {T: Type} (re: @reg_exp T) : bool :=
  match re with
  | EmptySet => false
  | EmptyStr => true
  | Char t => true
  | App r1 r2 => (re_not_empty r1) && (re_not_empty r2)
  | Union r1 r2 => (re_not_empty r1) || (re_not_empty r2)
  | Star r => true
  end.

Lemma re_not_empty_correct: forall T (re: @reg_exp T),
  (exists s, s =~ re) <-> re_not_empty re = true.
Proof.
  intros.
  split.
  - induction re.
    + intros [s H]. inversion H.
    + reflexivity.
    + reflexivity.
    + intros [s H]. inversion H. simpl.
      apply andb_true_iff. split.
      * apply IHre1. exists s1. apply H3.
      * apply IHre2. exists s2. apply H4.
    + intros [s H]. inversion H.
      * simpl.
        apply orb_true_iff. left.
        apply IHre1. exists s. apply H2.
      * simpl.
        apply orb_true_iff. right.
        apply IHre2. exists s. apply H1.
    + reflexivity.
  - induction re.
    + intros. discriminate H.
    + intros. exists []. apply MEmpty.
    + intros. exists [t]. apply MChar.
    + intros. inversion H.
      apply andb_true_iff in H1.
      destruct H1 as [H1 H2].
      induction IHre1. induction IHre2.
      exists (x ++ x0). apply MApp. apply H0. apply H3. apply H2. apply H1.
    + intros. inversion H.
      apply orb_true_iff in H1.
      destruct H1 as [H1 | H2].
      * induction IHre1. exists x. apply MUnionL. apply H0. apply H1.
      * induction IHre2. exists x. apply MUnionR. apply H0. apply H2.
    + intros. exists []. apply MStar0.
Qed.

(* The remember Tactic *)
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'.
  generalize dependent s2.
  induction H1.
  - discriminate.
  - discriminate.
  - discriminate.
  - discriminate.
  - discriminate.
  - injection Heqre'.
    intros. simpl. apply H0.
  - injection Heqre'.
    intros. rewrite <- app_assoc.
    apply MStarApp.
    + apply H1_.
    + apply IHexp_match2.
      * rewrite H. reflexivity.
      * apply H0.
Qed.

(* Exercise exp_match_ex2 *)
Lemma MStar'': forall T (s: list T) (re: reg_exp),
  s =~ Star re ->
  exists ss: list (list T), s = fold app ss [] /\
  exists s', In s' ss -> s' =~ re.
Proof.
  intros.
  remember (Star re) as re'.
  induction H.
  - discriminate.
  - discriminate.
  - discriminate.
  - discriminate.
  - discriminate.
  - exists []. simpl. split.
    + reflexivity.
    + exists []. intros. exfalso. apply H.
  - inversion Heqre'.
    apply IHexp_match2 in Heqre'.
    destruct Heqre' as [ss [H3 H4]].
    exists ([s1] ++ ss).
    split.
    + simpl. rewrite <- H3. reflexivity.
    + simpl. exists s1.
      intros. rewrite H2 in H. apply H.
Qed.

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

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.
  induction n.
  - reflexivity.
  - simpl. rewrite IHn, app_assoc. reflexivity.
Qed.

Import Coq.omega.Omega.
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.
Proof.
  intros T re s Hmatch.
  induction Hmatch
    as [ | x | s1 re1 s2 re2 Hmatch1 IH1 Hmatch2 IH2
       | s1 re1 re2 Hmatch IH | s2 re1 re2 Hmatch IH
       | re | s1 s2 re Hmatch1 IH1 Hmatch2 IH2 ].
  - (* MEmpty *)
    simpl. omega.
  - (* MChar *)
    simpl. omega.
  - (* MApp *)
    simpl. intros.
    rewrite app_length in H.
    apply Nat.add_le_cases in H.
    destruct H as [H | H].
    + apply IH1 in H. destruct H as [s3 [s4 [s5 [H1 [H2 H3]]]]].
      exists s3, s4, (s5 ++ s2). rewrite H1.
      rewrite <- app_assoc. rewrite <- app_assoc. split.
      * reflexivity.
      * split.
        { apply H2. }
        { intros. rewrite -> app_assoc. rewrite -> app_assoc.
          rewrite <- app_assoc with (m := (napp m s4)).
          apply MApp. apply H3. apply Hmatch2. }
    + apply IH2 in H. destruct H as [s3 [s4 [s5 [H1 [H2 H3]]]]].
      exists (s1 ++ s3), s4, s5. rewrite H1.
      rewrite <- app_assoc. split.
      * reflexivity.
      * split.
        { apply H2. }
        { intros. rewrite <- app_assoc.
          apply MApp. apply Hmatch1.
          apply H3. }
  - (* MUnionL *)
    simpl. intros.
    apply le_trans with (n := pumping_constant re1) in H.
    + apply IH in H. destruct H as [s2 [s3 [s4 [H1 [H2 H3]]]]].
      exists s2, s3, s4. rewrite H1. split.
      * reflexivity.
      * split.
        { apply H2. }
        { intros. apply MUnionL. apply H3. }
    + apply le_plus_l.
  - (* MUnionR *)
    simpl. intros.
    rewrite plus_comm in H.
    apply le_trans with (n := pumping_constant re2) in H.
    apply IH in H. destruct H as [s1 [s3 [s4 [H1 [H2 H3]]]]].
    + exists s1, s3, s4. rewrite H1. split.
      * reflexivity.
      * split.
        { apply H2. }
        { intros. apply MUnionR. apply H3. }
    + apply le_plus_l.
  - (* MStar0 *)
    simpl. intros. inversion H.
  - (* MStarApp *)
    simpl. intros. rewrite app_length in H.
    destruct s1.
    + destruct s2.
      * inversion H.
      * simpl in H. simpl in IH2. apply IH2 in H.
        destruct H as [s1 [s3 [s4 [H1 [H2 H3]]]]].
        rewrite H1. simpl. exists s1, s3, s4. split.
        { reflexivity. }
        { split.
          - apply H2.
          - apply H3. }
    + exists [], (x :: s1), s2. split.
      * reflexivity.
      * split.
        { intro. discriminate. }
        { intro. simpl. apply star_app.
          - induction m.
            + simpl. apply MStar0.
            + remember (x :: s1) as s1'.
              simpl. apply star_app.
              rewrite <- app_nil_r with (l := s1').
              apply MStarApp.
              apply Hmatch1.
              apply MStar0.
              apply IHm.
          - apply Hmatch2. }
Qed.

End Pumping.

(* Chap 7.5 Case Study: Improving Reflection *)
Theorem filter_not_empty_In: forall n l,
  filter (fun x => n =? x) l <> [] -> In n l.
Proof.
  intros n l.
  induction l.
  - simpl. intros. apply H. reflexivity.
  - simpl. destruct (n =? x) eqn: H.
    + intros. rewrite eqb_eq in H.
      left. rewrite H. reflexivity.
    + intros. right. apply IHl. apply H0.
Qed.

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

Theorem iff_reflect: forall P b, (P <-> b = true) -> reflect P b.
Proof.
  intros. destruct b.
  - apply ReflectT. apply H. reflexivity.
  - apply ReflectF. rewrite H. discriminate.
Qed.

(* Exercise reflect_iff *)
Theorem reflect_iff: forall P b, reflect P b -> (P <-> b = true).
Proof.
  intros P b H.
  induction H.
  - split.
    + reflexivity.
    + intros. apply H.
  - split.
    + intros. apply H in H0. exfalso. apply H0.
    + intros. discriminate H0.
Qed.

Lemma eqbP: forall n m, reflect (n = m) (n =? m).
Proof.
  intros. apply iff_reflect. rewrite eqb_eq. reflexivity.
Qed.

Theorem filter_not_empty_In': forall n l,
  filter (fun x => n =? x) l <> [] -> In n l.
Proof.
  intros n l.
  induction l.
  - simpl. intros. apply H. reflexivity.
  - simpl. destruct (eqbP n x) as [H | H].
    + intros. rewrite H. left. reflexivity.
    + intros. right. apply IHl. apply H0.
Qed.

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

(* Exercise eqbP_practice *)
Theorem eqbP_practice: forall n l,
  count n l = 0 -> ~ (In n l).
Proof.
  intros n l.
  induction l.
  - intros. simpl.
    unfold not. intros H'. apply H'.
  - intros. simpl.
    destruct (eqbP n x) as [H' | H'].
    + rewrite H' in H.
      simpl in H. rewrite <- eqb_refl in H.
      discriminate H.
    + unfold not. intros.
      destruct H0 as [H1 | H2].
      * unfold not in H'. symmetry in H1.
        apply H' in H1. apply H1.
      * simpl in H. unfold not in IHl.
        apply IHl in H2.
        apply H2.
        replace (n =? x) with false in H.
        simpl in H. apply H.
        destruct (n =? x).
        { discriminate. } { reflexivity. }
Qed.
(* Ques: too long? *)

(* Chap 7.6 Additional Exercises *)
(* Exercise nostutter_defn *)
Definition check_is_not_head {X: Type} (l: list X) (x: X) : Prop :=
  match l with
  | [] => True
  | h :: t => x <> h
  end.

Inductive nostutter {X: Type} : list X -> Prop :=
  | nostutter_nil: nostutter []
  | nostutter_add x l (H: check_is_not_head l x) (I: nostutter l): nostutter (x :: l).

Example test_nostutter_1: nostutter [3;1;4;1;5;6].
Proof.
  repeat constructor; apply eqb_neq; auto.
Qed.

Example test_nostutter_2: nostutter (@nil nat).
Proof.
  repeat constructor; apply eqb_neq; auto.
Qed.

Example test_nostutter_3: nostutter [5].
Proof.
  repeat constructor; apply eqb_false; auto.
Qed.

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

(* Exercise filter_challenge *)
Inductive merge_in_order {X: Type}: list X -> list X -> list X -> Prop :=
  | Empty_MIO: merge_in_order [] [] []
  | MergeLeft: forall l1 l2 l x, merge_in_order l1 l2 l -> merge_in_order (x :: l1) l2 (x :: l)
  | MergeRight: forall l1 l2 l x, merge_in_order l1 l2 l -> merge_in_order l1 (x :: l2) (x :: l).

Theorem merge_filter_only: forall X (l1 l2 l: list X) (test: X -> bool),
  merge_in_order l1 l2 l ->
  (forall x, In x l1 -> test x = true) ->
  (forall x, In x l2 -> test x = false) ->
  filter test l = l1.
Proof.
  intros.
  induction H.
  - reflexivity.
  - simpl. rewrite -> H0.
    + apply IHmerge_in_order in H1.
      rewrite H1. reflexivity.
      intros. apply H0. simpl. right. apply H2.
    + simpl. left. reflexivity.
  - simpl.
    destruct (test x) eqn: Htest.
    + assert (Hcontra: test x = false).
      { apply H1. simpl. left. reflexivity. }
      rewrite Hcontra in Htest.
      discriminate Htest.
    + apply IHmerge_in_order in H0.
      apply H0.
      intros. apply H1. simpl. right. apply H2.
Qed.

(* Exercise filter_challenge_2 *)
Print subseq.
Theorem filter_behavior: forall X (l sl: list X) (test: X -> bool),
  subseq sl l ->
  forallb test sl = true ->
  length sl <= length (filter test l).
Proof.
  intros X l sl test H1.
  induction H1.
  - intros H2. simpl. apply O_le_n.
  - intros H2. simpl.
    destruct (test x) eqn: Htest.
    + simpl. apply le_S. apply IHsubseq. apply H2.
    + simpl. apply IHsubseq. apply H2.
  - intros H2. simpl.
    destruct (test x) eqn: Htest.
    + simpl. apply n_le_m__Sn_le_Sm. apply IHsubseq.
      simpl in H2. rewrite Htest in H2. apply H2.
    + simpl in H2. rewrite Htest in H2. discriminate H2.
Qed.

(* Exercise palindromes *)
Inductive pal {X: Type}: list X -> Prop :=
  | Empty_P: pal []
  | One_P: forall c, pal [c]
  | Add_P: forall c l, pal l -> pal (c :: l ++ [c]).

Theorem pal_app_rev: forall X (l: list X), pal (l ++ rev l).
Proof.
  intros.
  induction l.
  - simpl. apply Empty_P.
  - simpl. rewrite app_assoc. apply Add_P, IHl.
Qed.

Theorem pal_rev: forall X (l: list X), pal l -> l = rev l.
Proof.
  intros.
  induction H.
  - reflexivity.
  - reflexivity.
  - simpl. rewrite rev_app_distr. rewrite <- IHpal. reflexivity.
Qed.

(* Exercise palindrome_converse *)
(*
   First we prove that:
   If the Prop has the following property:
     If a Prop is true for all the numbers less than n, then it's true for n.
   Then we can conclude the Prop is true for all natural numbers n.
*)
Lemma Prop_induction_for_nat: forall (P: nat -> Prop),
  (forall n, (forall m, m < n -> P m) -> P n) ->
  (forall n, P n).
Proof.
  intros.
  apply H.
  induction n.
  - intros. inversion H0.
  - apply H in IHn as Hn.
    intros.
    inversion H0.
    + apply Hn.
    + apply IHn. unfold lt. apply H2.
Qed.

(*
   Then we prove a special nat induction way which is:
   The Prop is true for 0 and 1, and if the Prop is true for n, then it's true for (n + 2).
   From this we can conclude that the Prop is true for all n.
   We cannot use simple induction here because even and odd should be split, so we use the
   Prop_induction_for_nat we state before.
*)
Lemma nat_induction: forall (P: nat -> Prop),
  P 0 -> P 1 -> (forall n, P n -> P (n + 2)) ->
  (forall n, P n).
Proof.
  intros.
  apply Prop_induction_for_nat.
  intros m H2.
  destruct m.
  - apply H.
  - destruct m.
    + apply H0.
    + assert (I: S (S m) = m + 2). { rewrite -> plus_comm. reflexivity. }
      rewrite I. apply H1.
      apply H2. unfold lt.
      apply le_S. apply le_n.
Qed.

(*
   Next, we think about Prop connected to the list.
   Because we want to prove palindromes_converse Theorem, so we need to reduce the length
   twice a step. Then we need the following Lemma. It state if we can prove that forall n,
   lists that have length n satisfy Prop, we can prove all the lists satisfy the Prop.
   This lemma is quite easy to prove though, by connecting n with (length l).
*)
Lemma length_induction: forall X (P: list X -> Prop),
  (forall n l, length l = n -> P l) ->
  forall l, P l.
Proof.
  intros.
  apply H with (n := length l).
  reflexivity.
Qed.

(*
   This is Lemma state that "list l is empty" equals to "list (rev l) is empty"
*)
Lemma rev_empty_eq_empty: forall X (l: list X), rev l = [] <-> l = [].
Proof.
  split.
  - intros.
    destruct l eqn: Hl.
    + reflexivity.
    + rewrite <- rev_involutive with (l := (x :: l0)).
      rewrite H. reflexivity.
  - intros. rewrite H. reflexivity.
Qed.

(*
   This is a Lemma shows that if a list has length (n + 2), we can get its head and tail
   off the list, then its length becomes n.
*)
Lemma list_length_SS: forall X (l: list X) n,
  (length l = n + 2) -> exists l' x y, l = [x] ++ l' ++ [y] /\ length l' = n.
Proof.
  intros.
  destruct l.
  - rewrite <- plus_comm in H. simpl in H. discriminate.
  - rewrite <- plus_comm in H. simpl in H. injection H as H.
    destruct (rev l) eqn: Hr.
    + assert (Hempty: l = []).
      { apply rev_empty_eq_empty, Hr. }
      rewrite Hempty in H. simpl in H. discriminate.
    + exists (rev l0), x, x0.
      assert(I: l = rev l0 ++ [x0]).
        { rewrite <- rev_involutive with (l := l).
          rewrite Hr. simpl. reflexivity. }
      split.
      * rewrite I. simpl. reflexivity.
      * rewrite -> I in H.
        rewrite app_length in H.
        simpl in H.
        rewrite <- plus_n_Sm in H.
        injection H as H.
        rewrite <- plus_n_O in H.
        apply H.
Qed.

(*
   This is a Lemma shows our induction about palindromes:
   i) Empty list satisfies the Prop
   ii) List which has only one element satisfies.
   iii) If we have a satisfied list l, we can add an element to the list head and add
   add an element to its tail, the new list still satisfies.
   If a Prop satisfies all the point above, then it's true for all the list.

   To prove this, we start with a induction on length using length_induction.
   and we make Pn as our new Prop (nat (here is length) -> Prop).
   i) try to prove Pn 0 is true.
   ii) try to prove Pn 1 is true.
   iii) try to prove if Pn n is true, then Pn (n + 2) is true.
        In this step, we may use the Lemma list_length_SS above to get the head and tail
        of the list and reduce the length by 2, so that we can use Pn n.
   iv) if we prove the things above, then we can prove forall list it is true.
       By introducing the length n of any list, and using nat_induction to prove Pn n is
       true).
*)
Lemma palindrome_induction: forall X (P: list X -> Prop),
  P [] ->
  (forall x: X, P [x]) ->
  (forall (x y: X) (l: list X), P l -> P (x :: l ++ [y])) ->
  (forall l, P l).
Proof.
  intros.
  apply length_induction.
  remember (fun n => (forall l, length l = n -> P l)) as Pn.
  assert (Pn0: Pn 0).
  {
    rewrite HeqPn. intros. destruct l0.
    - apply H.
    - simpl in H2. discriminate.
  }
  assert (Pn1: Pn 1).
  {
    rewrite HeqPn. intros.
    destruct l0.
    - apply H.
    - destruct l0.
      + apply H0.
      + simpl in H2. discriminate.
  }
  assert (PnTrans: forall n, Pn n -> Pn (n + 2)).
  {
    rewrite HeqPn.
    intros.
    apply list_length_SS in H3 as H4.
    destruct H4 as [l' [x [y [H4 H5]]]].
    apply H2 in H5.
    rewrite H4. apply H1, H5.
  }
  intros n.
  assert (Pnn: Pn n).
  { apply nat_induction. apply Pn0. apply Pn1. apply PnTrans. }
  rewrite HeqPn in Pnn.
  apply Pnn.
Qed.

Lemma equal_length_eq: forall X (l1 l2: list X),
  l1 = l2 -> length l1 = length l2.
Proof.
  intros.
  rewrite H.
  reflexivity.
Qed.

Lemma app_one: forall X (l1 l2: list X) x y, l1 ++ [x] = l2 ++ [y] -> l1 = l2 /\ x = y.
Proof.
  intros.
  generalize dependent l2.
  induction l1.
  - intros. destruct l2.
    + split. reflexivity. inversion H. rewrite H1 in H. reflexivity.
    + apply equal_length_eq in H. injection H as H.
      rewrite app_length in H. simpl in H. rewrite plus_comm in H. discriminate.
  - intros. destruct l2.
    + apply equal_length_eq in H. injection H as H.
      rewrite app_length in H. simpl in H. rewrite plus_comm in H. discriminate.
    + simpl. inversion H. rewrite H1 in *.
      apply IHl1 in H2. destruct H2 as [H2 H3]. split.
      * rewrite H2. reflexivity.
      * apply H3.
Qed.

Lemma rev_back_eq_front: forall X (l: list X) x,
  rev (l ++ [x]) = x :: rev l.
Proof.
  intros.
  induction l.
  - reflexivity.
  - simpl. rewrite IHl. simpl. reflexivity.
Qed.

(*
   We can use palindrome_induction to prove this theorem, with P := l => l = rev l -> pal l.
   Length 0, and length 1 is easy to prove.
   How about length n + 2? We can use the result of length n to prove that x = y.
*)
Theorem palindrome_converse: forall X (l: list X), l = rev l -> pal l.
Proof.
  intros X l.
  apply palindrome_induction with (P := fun l => l = rev l -> pal l).
  - intros. apply Empty_P.
  - intros. apply One_P.
  - intros. simpl in *.
    replace (x :: l0 ++ [y]) with ((x :: l0) ++ [y]) in *.
    apply app_one in H0.
    destruct H0 as [H1 H2].
    simpl. rewrite H2 in *. apply Add_P.
    apply H. rewrite rev_back_eq_front in H1.
    injection H1 as H1. apply H1.
    simpl. reflexivity.
Qed.

(* Exercise NoDup *)
Inductive NoDup {X: Type}: list X -> Prop :=
  | Empty_ND: NoDup []
  | Add_ND: forall x l, NoDup l -> ~ (In x l) -> NoDup (x :: l).

Definition disjoint {X: Type} (l1 l2: list X) :=
  forall x, In x l1 -> ~ (In x l2).

Example NoDupTest1: NoDup [1;2;3;4].
Proof.
  apply Add_ND. apply Add_ND. apply Add_ND. apply Add_ND. apply Empty_ND.
  - simpl. unfold not. intros. apply H.
  - simpl. unfold not. intros. destruct H as [H | H].
    + apply eqb_eq in H. simpl in H. discriminate H.
    + apply H.
  - simpl. unfold not. intros. destruct H as [H | [H | H]].
    + apply eqb_eq in H. discriminate H.
    + apply eqb_eq in H. discriminate H.
    + apply H.
  - simpl. unfold not. intros. destruct H as [H | [H | [H | H]]].
    + apply eqb_eq in H. discriminate H.
    + apply eqb_eq in H. discriminate H.
    + apply eqb_eq in H. discriminate H.
    + apply H.
Qed.

Theorem NoDup_app: forall X (l1 l2: list X),
  NoDup l1 -> NoDup l2 ->
  disjoint l1 l2 ->
  NoDup (l1 ++ l2).
Proof.
  intros X l1 l2.
  intros H1.
  induction H1.
  - intros. simpl. apply H.
  - intros. simpl. apply Add_ND. apply IHNoDup.
    + apply H0.
    + unfold disjoint in *. intros. apply H2. simpl. right. apply H3.
    + unfold not. intros. apply In_app_iff in H3.
      destruct H3 as [H3 | H3].
      * apply H in H3. apply H3.
      * unfold not in H2. apply H2 with (x0 := x).
        { simpl. left. reflexivity. }
        { apply H3. }
Qed.

(* Exercise pigeonhole_principle *)
Lemma in_split: forall (X: Type) (x: X) (l: list X),
  In x l -> exists l1 l2, l = l1 ++ x :: l2.
Proof.
  intros X x l.
  induction l.
  - intros. simpl in H. destruct H.
  - intros. simpl in H.
    destruct H as [H | H].
    + exists []. exists l. simpl. rewrite H. reflexivity.
    + apply IHl in H.
      destruct H as [l1 [l2 H]].
      exists (x0 :: l1). exists l2. simpl. rewrite H. reflexivity.
Qed.

Inductive repeats {X: Type}: list X -> Prop :=
  | First_R: forall l x, In x l -> repeats (x :: l)
  | Add_R: forall l x, repeats l -> repeats (x :: l).

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'].
  - intros. simpl in H1. inversion H1.
  - intros. simpl in H1.
    assert(Hex: In x l1' \/ ~ In x l1').
    { apply H. }
    destruct Hex as [Hex | Hex].
    + apply First_R, Hex.
    + apply Add_R.
      assert(I: In x l2). { apply H0. simpl. left. reflexivity. }
      apply in_split in I.
      destruct I as [l1 [l3 I]].
      apply IHl1' with (l2 := l1 ++ l3).
      * apply H.
      * intros.
        rewrite I in H0.
        assert (H': x <> x0).
        { intros contra. rewrite <- contra in H2. apply Hex in H2. apply H2. }
        assert (H3: In x0 l1' <-> In x0 (x :: l1')).
        { split.
          - intros. simpl. right. apply H3.
          - intros. destruct H3.
            + apply H' in H3. inversion H3.
            + apply H3. }
        rewrite H3 in H2.
        apply H0 in H2.
        apply In_app_iff in H2.
        apply In_app_iff.
        destruct H2.
        { left. apply H2. }
        { right. simpl in H2.
          destruct H2.
          - apply H' in H2. inversion H2.
          - apply H2.
        }
      * rewrite I in H1.
        rewrite app_length, plus_comm in H1.
        simpl in H1. unfold lt in *.
        apply le_pred in H1. simpl in H1.
        rewrite app_length, plus_comm.
        apply H1.
Qed.

(* Extended Exercise: A Verified Regular-Expression Matcher *)
Require Export Coq.Strings.Ascii.
Definition string := list ascii.

Lemma provable_equiv_true: forall (P: Prop), P -> (P <-> True).
Proof.
  intros.
  split.
  - intros. constructor.
  - intros. apply H.
Qed.

Lemma not_equiv_false: forall (P: Prop), ~P -> (P <-> False).
Proof.
  intros.
  split.
  - intros. apply H in H0. apply H0.
  - intros. exfalso. apply H0.
Qed.

Lemma null_matches_none: forall (s: string), (s =~ EmptySet) <-> False.
Proof.
  intros.
  apply not_equiv_false.
  unfold not.
  intros. inversion H.
Qed.

Lemma empty_matches_eps: forall (s: string), (s =~ EmptyStr) <-> s = [].
Proof.
  intros. split.
  - intros. inversion H. reflexivity.
  - intros. rewrite H. apply MEmpty.
Qed.

Lemma empty_nomatch_ne: forall (a: ascii) (s: string), (a :: s =~ EmptyStr) <-> False.
Proof.
  intros. apply not_equiv_false.
  unfold not. intros.
  inversion H.
Qed.

Lemma char_nomatch_char: forall (a b: ascii) s, b <> a -> (b :: s =~ Char a) <-> False.
Proof.
  intros. apply not_equiv_false.
  unfold not. intros.
  inversion H0. apply H, H4.
Qed.

Lemma char_eps_suffix: forall (a: ascii) s, a :: s =~ Char a <-> s = [].
Proof.
  intros. split.
  - intros. inversion H. reflexivity.
  - intros. rewrite H. apply MChar.
Qed.

Lemma app_exists: forall (s: string) re0 re1,
  s =~ App re0 re1 <-> exists s0 s1, s = s0 ++ s1 /\ s0 =~ re0 /\ s1 =~ re1.
Proof.
  intros. split.
  - intros. inversion H.
    exists s1, s2.
    split.
    + reflexivity.
    + split. apply H3. apply H4.
  - intros. destruct H as [s0 [s1 [H1 [H2 H3]]]].
    rewrite H1. apply MApp. apply H2. apply H3.
Qed.

(* Exercise app_ne *)
Lemma app_nil_l: forall X (l: list X), [] ++ l = l.
Proof. reflexivity. Qed.

Lemma app_ne: forall (a: ascii) s re0 re1,
  a :: s =~ (App re0 re1) <->
  ([] =~ re0 /\ a :: s =~ re1) \/
  (exists s0 s1, s = s0 ++ s1 /\ a :: s0 =~ re0 /\ s1 =~ re1).
Proof.
  intros. split.
  - intros. inversion H.
    destruct s1.
    + left. split. apply H3. apply H4.
    + right. exists s1, s2. simpl in H1. injection H1. intros.
      split. symmetry. apply H5.
      split. rewrite <- H6. apply H3.
      apply H4.
  - intros. destruct H as [H | H].
    + destruct H as [H1 H2].
      rewrite <- app_nil_l with (l := (a :: s)).
      apply MApp. apply H1. apply H2.
    + destruct H as [s0 [s1 [H1 [H2 H3]]]].
      replace (a :: s) with ((a :: s0) ++ s1).
      apply MApp. apply H2. apply H3.
      simpl. rewrite H1. reflexivity.
Qed.

Lemma union_disj: forall (s: string) re0 re1,
  s =~ Union re0 re1 <-> s =~ re0 \/ s =~ re1.
Proof.
  intros. split.
  - intros. inversion H.
    + left. apply H2.
    + right. apply H1.
  - intros. destruct H as [H1 | H2].
    + apply MUnionL, H1.
    + apply MUnionR, H2.
Qed.

(* Exercise star_ne *)
Lemma star_ne: forall (a: ascii) s re, a :: s =~ Star re <->
  exists s0 s1, s = s0 ++ s1 /\ a :: s0 =~ re /\ s1 =~ Star re.
Proof.
  intros. split.
  - intros.
    remember (Star re) as re'.
    remember (a :: s) as s'.
    induction H.
    + intros. inversion Heqs'.
    + intros. inversion Heqre'.
    + intros. inversion Heqre'.
    + intros. inversion Heqre'.
    + intros. inversion Heqre'.
    + intros. inversion Heqs'.
    + intros.
      destruct s1.
      * simpl in Heqs'.
        apply IHexp_match2 in Heqre'. apply Heqre'. apply Heqs'.
      * simpl in Heqs'.
        injection Heqs' as H1 H2.
        exists s1, s2. split.
        { rewrite H2. reflexivity. }
        { split. rewrite <- H1. injection Heqre' as Hre. rewrite <- Hre. apply H.
                 apply H0.
        }
  - intros. destruct H as [s0 [s1 [H1 [H2 H3]]]].
    rewrite H1.
    replace (a :: s0 ++ s1) with ((a :: s0) ++ s1).
    apply MStarApp.
    + apply H2.
    + apply H3.
    + reflexivity.
Qed.

Definition refl_matches_eps m :=
  forall re : @reg_exp ascii, reflect ([ ] =~ re) (m re).

(* Exercise match_eps *)
Print reg_exp.
Fixpoint match_eps (re: @reg_exp ascii) : bool :=
  match re with
  | EmptySet => false
  | EmptyStr => true
  | Char t => false
  | App re0 re1 => (match_eps re0) && (match_eps re1)
  | Union re0 re1 => (match_eps re0) || (match_eps re1)
  | Star re => true
  end.

Lemma app_nil_both_nil: forall X (l1 l2: list X),
  l1 ++ l2 = [] <-> l1 = [] /\ l2 = [].
Proof.
  split.
  - intros. induction l1.
    + simpl in H. split. reflexivity. apply H.
    + simpl in H. discriminate H.
  - intros. destruct H as [H1 H2].
    rewrite H1, H2. reflexivity.
Qed.

Lemma match_eps_refl: refl_matches_eps match_eps.
Proof.
  unfold refl_matches_eps.
  intros.
  apply iff_reflect.
  split.
  - intros.
    induction re.
    + inversion H.
    + reflexivity.
    + inversion H.
    + inversion H.
      destruct s1 eqn: Hs1.
      * simpl in *. rewrite H1 in H4.
        apply andb_true_iff.
        split. apply IHre1, H3. apply IHre2, H4.
      * simpl in *.
        discriminate.
    + inversion H.
      * simpl in *.
        apply orb_true_iff. left. apply IHre1, H2.
      * simpl in *.
        apply orb_true_iff. right. apply IHre2, H1.
    + reflexivity.
  - intros. induction re.
    + discriminate H.
    + apply MEmpty.
    + discriminate H.
    + simpl in H. apply andb_true_iff in H. destruct H as [H1 H2].
      apply IHre1 in H1; apply IHre2 in H2.
      assert(H: [] ++ [] =~ App re1 re2).
      { apply MApp. apply H1. apply H2. }
      simpl in H. apply H.
    + simpl in H. apply orb_true_iff in H. destruct H as [H1 | H2].
      * apply IHre1 in H1. apply MUnionL. apply H1.
      * apply IHre2 in H2. apply MUnionR. apply H2.
    + apply MStar0.
Qed.

Definition is_der re (a: ascii) re' :=
  forall s, a :: s =~ re <-> s =~ re'.

Definition derives d := forall a re, is_der re a (d a re).

(* Exercise derive *)
Fixpoint derive (a: ascii) (re: @reg_exp ascii): @reg_exp ascii :=
  match re with
  | EmptySet => EmptySet
  | EmptyStr => EmptyStr
  | Char t =>
      if (nat_of_ascii a) =? (nat_of_ascii t) then EmptyStr
      else re
  | App re1 re2 =>
      if (match_eps re1) then Union (derive a re2) (App (derive a re1) re2)
      else App (derive a re1) re2
  | Union re1 re2 => Union (derive a re1) (derive a re2)
  | Star re => Star (derive a re)
  end.
(* Not sure about it *)

Example c := ascii_of_nat 99.
Example d := ascii_of_nat 100.

Example test_der0 : match_eps (derive c (EmptySet)) = false.
Proof. reflexivity. Qed.

Example test_der1 : match_eps (derive c (Char c)) = true.
Proof. reflexivity. Qed.

Example test_der2 : match_eps (derive c (Char d)) = false.
Proof. reflexivity. Qed.

Example test_der3 : match_eps (derive c (App (Char c) EmptyStr)) = true.
Proof. reflexivity. Qed.

Example test_der4 : match_eps (derive c (App EmptyStr (Char c))) = true.
Proof. reflexivity. Qed.

Example test_der5 : match_eps (derive c (Star (Char c))) = true.
Proof. reflexivity. Qed.

Example test_der6 :
  match_eps (derive d (derive c (App (Char c) (Char d)))) = true.
Proof. reflexivity. Qed.

Example test_der7 :
  match_eps (derive d (derive c (App (Char d) (Char c)))) = false.
Proof. reflexivity. Qed.

(* Exercise derive_corr *)
Lemma derive_corr : derives derive.
Proof.
  unfold derives.
  unfold is_der.
  split.
  - generalize dependent a.
    generalize dependent s.
    induction re.
    + intros. inversion H.
    + intros. subst. inversion H.
    + intros. subst. inversion H.
      simpl. rewrite <- Induction.eqb_refl. apply MEmpty.
    + intros. simpl.
      apply app_ne in H.
      destruct H as [[H1 H2] | [s0 [s1 [H1 [H2 H3]]]]].
      * destruct (match_eps re1) eqn: Hmatch.
        { apply MUnionL. apply IHre2. apply H2. }
        { admit. }
      * destruct (match_eps re1) eqn: Hmatch.
        { admit. }
        { admit. }
    + intros. simpl. inversion H; subst.
      * apply MUnionL. apply IHre1. apply H2.
      * apply MUnionR. apply IHre2. apply H1.
    + intros. simpl.
      apply star_ne in H.
      destruct H as [s1 [s2 [H1 [H2 H3]]]].
      admit.
  - intros.
    generalize dependent s.
    generalize dependent a.
    induction re.
    + intros. inversion H.
    + intros.

Admitted.

Definition matches_regex m: Prop :=
  forall (s: string) re, reflect (s =~ re) (m s re).

(* Exercise regex_match *)
Fixpoint regex_match (s: string) (reg: @reg_exp ascii) : bool.
Admitted.

(* Exercise regex_refl *)
Theorem regex_refl: matches_regex regex_match.
Proof.
Admitted.


Module NatPlayground2.

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

Compute (plus 3 2).

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

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

Example test_minus1: (minus 3 2) = 1.
Proof. simpl. reflexivity.  Qed.

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

Example test_exp1: (exp 2 10) = 1024.
Proof. simpl. reflexivity.  Qed.

End NatPlayground2.


From LF Require Export Basics.

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

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

    Theorem mult_0_r : forall n:nat,
    n * 0 = 0.
    Proof.
        intros n. induction 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.
        - simpl. reflexivity.
        - simpl. rewrite->IHn. reflexivity.
    Qed.

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

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

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

    Lemma double_plus: forall n, double n = n+n .
    Proof.
        intros n . induction n.
        - reflexivity.
        - simpl. rewrite->IHn.  rewrite->plus_n_Sm. reflexivity.
    Qed.

    Theorem evenb_S : forall n:nat,
    evenb (S n) = negb (evenb n).
    Proof.
        intros n. induction n.
        - simpl. reflexivity.
        - rewrite->IHn. rewrite->negb_involutive. simpl. reflexivity.
    Qed.

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

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

    Theorem mult_plus_distr_1: forall n m:nat,
    n* S m = n + n * m.
    Proof.
        intros n m. induction n.
        - simpl. reflexivity.
        - simpl. rewrite->IHn. rewrite->plus_swap. reflexivity.
    Qed.

    Theorem mult_comm: forall m n:nat,
    m*n = n*m .
    Proof.
        intros m n. induction m.
        - simpl. rewrite->mult_0_r. reflexivity.
        - simpl. rewrite->IHm. rewrite->mult_plus_distr_1. reflexivity.
    Qed.

    Theorem leb_refl : forall n:nat,
    true = (n <=? n).
    Proof.
        intros n. induction n.
        - reflexivity.
        - simpl. rewrite<-IHn. reflexivity.
    Qed.

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

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

    Theorem plus_ble_compat_l : forall n m p : nat,
    n <=? m = true -> (p + n) <=? (p + m) = true.
    Proof.
        intros n m p. intros H. induction p.
        - simpl. rewrite->H. reflexivity.
        - simpl. rewrite->IHp. reflexivity.
    Qed.

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

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

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

    Theorem mult_plus_distr_r : forall n m p : nat,
    (n + m) * p = (n * p) + (m * p).
    Proof.
        intros n m p.
        induction p.
        {rewrite->mult_0_r. rewrite->mult_0_r. rewrite->mult_0_r. reflexivity. }
        {
            rewrite->mult_plus_distr_1. rewrite->mult_plus_distr_1. rewrite->mult_plus_distr_1.
            rewrite->plus_swap. rewrite->IHp.
            rewrite<-plus_assoc. rewrite<-plus_assoc. rewrite->plus_swap.
            reflexivity.
        }
    Qed.

    Theorem mult_assoc : forall n m p : nat,
    n * (m * p) = (n * m) * p.
    Proof.
        intros n m p.
        induction n.
        - reflexivity.
        - simpl. rewrite->IHn. rewrite<-mult_plus_distr_r. reflexivity.
    Qed.

    Theorem eqb_refl: forall n:nat,
    true = (n =? n).
    Proof.
        intros n. induction n.
        - reflexivity.
        - simpl. rewrite->IHn. reflexivity.
    Qed.

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

    Theorem bin_to_nat_pres_incr: forall n:bin,
    bin_to_nat (incr n) = S (bin_to_nat n).
    Proof.
        intros n. induction n.
        - reflexivity.
        - reflexivity.
        - {simpl.
        rewrite->IHn.
        rewrite->plus_n_Sm.
        replace (bin_to_nat n + S (bin_to_nat n)) with (S (bin_to_nat n) + (bin_to_nat n)).
        - rewrite->plus_n_Sm. reflexivity.
        - rewrite->plus_comm. reflexivity.
        }
    Qed.

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

    Lemma nat_to_bin_pres_incr: forall n:nat,
    incr (nat_to_bin n) = nat_to_bin (S n).
    Proof.
        intros n. induction n.
        - reflexivity.
        - reflexivity.
    Qed.

    Theorem nat_bin_nat: forall n,
    bin_to_nat (nat_to_bin n) =n .
    Proof.
        intros n. induction n.
        - reflexivity.
        - simpl. rewrite->bin_to_nat_pres_incr. rewrite->IHn. reflexivity.
    Qed.