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

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 in this definition: *)

Inductive natprod : Type :=
  pair : nat -> nat -> natprod.

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

(** We can construct an element of [natprod] like this: *)

Check (pair 3 5).

(** Here are two simple function definitions for extracting the
    first and second components of a pair.  (The definitions also
    illustrate how to do pattern matching on two-argument
    constructors.) *)

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.

Eval compute in (fst (pair 3 5)).
(* ===> 3 *)

(** Since pairs are used quite a bit, 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 notation can be used both in expressions and in
    pattern matches (indeed, we've seen it already in the previous
    chapter -- this notation is provided as part of the standard
    library): *)

Eval compute in (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.

(** Let's try and prove a few simple facts about pairs.  If we
    state the lemmas in a particular (and slightly peculiar) way, we
    can prove them 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.

(** Note that [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].

    Notice that, unlike for [nat]s, [destruct] doesn't generate an
    extra subgoal here.  That's because [natprod]s can only be
    constructed in one way.  *)

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

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

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

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

(** Generalizing the definition of pairs a little, 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 : natlist
  | cons : nat -> natlist -> 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 two 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 fully understand these declarations,
    but in case you are interested, here is roughly what's going on.

    The [right associativity] annotation tells Coq how to parenthesize
    expressions involving several 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])].

   (By the way, it's worth noting in passing that 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. *)

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

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

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

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

(** Actually, [app] will be used a lot in some parts of what
    follows, so it is 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.

(** 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").
    Of course, the empty list has no first element, so 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.

(** **** Exercise: 2 stars (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
  | 0 :: t => nonzeros t
  | h :: t => h :: nonzeros t
  end.

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

Fixpoint oddmembers (l:natlist) : natlist :=
  match l with
  | nil => nil
  | h :: t =>
    match oddb h with
    | true => h :: oddmembers t
    | false => oddmembers t
    end
  end.

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

Fixpoint countoddmembers (l:natlist) : nat :=
  length (oddmembers l).

Example test_countoddmembers1:    countoddmembers [1;0;3;1;4;5] = 4.
 reflexivity. Qed.
Example test_countoddmembers2:    countoddmembers [0;2;4] = 0.
 reflexivity. Qed.
Example test_countoddmembers3:    countoddmembers nil = 0.
 reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (alternate) *)
(** Complete the definition of [alternate], which "zips up" 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 requires
    defining a new kind of pairs, but this is not the only way.)  *)

Fixpoint alternate (l1 l2 : natlist) : natlist :=
  match l1 with
  | nil => l2
  | h1 :: t1 => (* h :: alternate l2 t elegant but doesn't work*)
    match l2 with
    | nil => l1
    | h2 :: t2 => h1 :: h2 :: alternate t1 t2
    end
  end.

Example test_alternate1:        alternate [1;2;3] [4;5;6] = [1;4;2;5;3;6].
  reflexivity. Qed.
Example test_alternate2:        alternate [1] [4;5;6] = [1;4;5;6].
  reflexivity. Qed.
Example test_alternate3:        alternate [1;2;3] [4] = [1;4;2;3].
  reflexivity. Qed.
Example test_alternate4:        alternate [] [20;30] = [20;30].
  reflexivity. Qed.
(** [] *)

(* ###################################################### *)
(** ** Bags via Lists *)

(** A [bag] (or [multiset]) is like a set, but each element can appear
    multiple times instead of just once.  One reasonable
    implementation of bags is to represent a bag of numbers as a
    list. *)

Definition bag := natlist.

(** **** Exercise: 3 stars (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 => 0
  | h :: t =>
    match beq_nat h v with
    | true => S (count v t)
    | false => count v t
    end
  end.
(** All these proofs can be done just by [reflexivity]. *)

Example test_count1:              count 1 [1;2;3;1;4;1] = 3.
  reflexivity. Qed.
Example test_count2:              count 6 [1;2;3;1;4;1] = 0.
  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, 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.
  reflexivity. Qed.

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

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

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

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

(** **** Exercise: 3 stars, optional (bag_more_functions) *)
(** Here are some more bag functions for you to practice with. *)

Fixpoint remove_one (v:nat) (s:bag) : bag :=
  (* When remove_one is applied to a bag without the number to remove,
     it should return the same bag unchanged. *)
  match s with
  | nil => nil
  | h :: t =>
    match beq_nat h v with
    | true => t
    | false => h :: remove_one v t
    end
  end.

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

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

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

Fixpoint subset (s1:bag) (s2:bag) : bool :=
  match s2 with
  | nil =>
    match s1 with
    | nil => true
    | _ => false
    end
  | h :: t => subset (remove_one h s1) t
  end.

(* should better say that this is "subbag" function, because of the second example. *)
Example test_subset1:              subset [1;2] [2;1;4;1] = true.
  reflexivity. Qed.
Example test_subset2:              subset [1;2;2] [2;1;4;1] = false.
  reflexivity. Qed.
(** [] *)

(** **** Exercise: 3 stars (bag_theorem) *)
(** Write down an interesting 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! *)

(*
 * add an element to the bag, and counting its occurrence,
 * is the same as taking the successor of the result of counting
 * on the original bag
 *)
Theorem count_add_theorem: forall v : nat, forall s : bag,
  count v (add v s) = S (count v s).
Proof.
  intros v k. simpl.
  assert (forall n : nat, beq_nat n n = true).
    intros n. induction n as [|n'].
    Case "n = 0". reflexivity.
    Case "n = S n'". simpl. rewrite IHn'. reflexivity.
  assert (beq_nat v v = true). apply H. rewrite H0.
  reflexivity. Qed.
(** [] *)

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

(** Just as with 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 match position
    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'].
  Case "l = nil".
    reflexivity.
  Case "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 example proofs will not get you very far!  It is
    very important to work through the details of each one, using Coq
    and thinking about what each step of the proof achieves.
    Otherwise it is more or less guaranteed that the exercises will
    make no sense. *)

(* ###################################################### *)
(** ** Induction on Lists *)

(** Proofs by induction over datatypes like [natlist] are
    perhaps a little less familiar than standard natural number
    induction, but the basic idea is equally simple.  Each [Inductive]
    declaration defines a set of data values that can be built up from
    the declared constructors: a boolean can be either [true] or
    [false]; a number can be either [O] or [S] applied to a 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 things together establish the
    truth of [P] for all lists [l].  Here's a concrete example: *)

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

(** Again, this Coq proof is not especially illuminating as a
    static written 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.  *)

(** _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.  []

  Here is a similar example to be worked together in class: *)

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'].
  Case "l1 = nil".
    reflexivity.
  Case "l1 = cons".
    simpl. rewrite -> IHl1'. reflexivity.  Qed.

(** For a slightly more involved example of an inductive proof
    over lists, suppose we define a "cons on the right" function
    [snoc] like this... *)

Fixpoint snoc (l:natlist) (v:nat) : natlist :=
  match l with
  | nil    => [v]
  | h :: t => h :: (snoc t v)
  end.

(** ... and use it to define a list-reversing function [rev]
    like this: *)

Fixpoint rev (l:natlist) : natlist :=
  match l with
  | nil    => nil
  | h :: t => snoc (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.

(** Now let's prove some more list theorems using our newly
    defined [snoc] and [rev].  For something a little more challenging
    than the inductive proofs we've seen so far, let's prove that
    reversing a list does not change its length.  Our first attempt at
    this proof 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'].
  Case "l = []".
    reflexivity.
  Case "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 [snoc], but we don't have any equations
       in either the immediate context or the global
       environment that have anything to do with [snoc]!

       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 about [snoc] that would have
    enabled us to make progress and prove it as a separate lemma.
*)

Theorem length_snoc : forall n : nat, forall l : natlist,
  length (snoc l n) = S (length l).
Proof.
  intros n l. induction l as [| n' l'].
  Case "l = nil".
    reflexivity.
  Case "l = cons n' l'".
    simpl. rewrite -> IHl'. reflexivity.  Qed.

(**
    Note that we make the lemma as _general_ as possible: in particular,
    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 much 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'].
  Case "l = nil".
    reflexivity.
  Case "l = cons".
    simpl. rewrite -> length_snoc.
    rewrite -> IHl'. reflexivity.  Qed.

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

    _Theorem_: For all numbers [n] and lists [l],
       [length (snoc l n) = S (length l)].

    _Proof_: By induction on [l].

    - First, suppose [l = []].  We must show
        length (snoc [] n) = S (length []),
      which follows directly from the definitions of
      [length] and [snoc].

    - Next, suppose [l = n'::l'], with
        length (snoc l' n) = S (length l').
      We must show
        length (snoc (n' :: l') n) = S (length (n' :: l')).
      By the definitions of [length] and [snoc], this
      follows from
        S (length (snoc l' n)) = S (S (length l')),
]]
      which is immediate from 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 (snoc (rev l') n) = S (length l')
        which, by the previous lemma, is the same as
          S (length (rev l')) = S (length l').
        This is immediate from the induction hypothesis. [] *)

(** Obviously, 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 (since we can easily work
    them 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 more like this: *)

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

    _Proof_: First, observe that
       length (snoc l n) = S (length l)
     for any [l].  This follows by a straightforward induction on [l].
     The main property now follows by another straightforward
     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 on 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
    present purposes. *)

(* ###################################################### *)
(** ** [SearchAbout] *)

(** We've seen that proofs can make use of other theorems we've
    already proved, using [rewrite], and later we will see other ways
    of reusing previous theorems.  But in order to refer to a theorem,
    we need to know its name, and remembering the names of all the
    theorems we might ever want to use can become quite difficult!  It
    is often hard even to remember what theorems have been proven,
    much less what they are named.

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

(*  SearchAbout rev. *)

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

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

(** **** Exercise: 3 stars (list_exercises) *)
(** More practice with lists. *)

Theorem app_nil_end : forall l : natlist,
  l ++ [] = l.
Proof.
  intros l. induction l as [|h t].
  Case "l = nil". reflexivity.
  Case "l = h :: t". simpl. rewrite IHt. reflexivity. Qed.

Lemma rev_involutive_helper : forall h : nat, forall t : natlist,
  rev (snoc t h) = h :: rev t.
Proof.
  intros h t. induction t as [|h1 t1].
  Case "t = nil". reflexivity.
  Case "t = h1 t1". simpl. rewrite IHt1. reflexivity.
Qed.

Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  intros l. induction l as [|h t].
  Case "l = nil". reflexivity.
  Case "l = h t". simpl.
    rewrite rev_involutive_helper. rewrite IHt. reflexivity.
Qed.

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

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

Theorem snoc_append : forall (l:natlist) (n:nat),
  snoc l n = l ++ [n].
Proof.
  intros l n. induction l as [|h t].
  Case "l = nil". reflexivity.
  Case "l = h t". simpl. rewrite IHt. reflexivity.
Qed.

Theorem distr_rev : forall l1 l2 : natlist,
  rev (l1 ++ l2) = (rev l2) ++ (rev l1).
Proof.
  intros l1 l2. induction l1 as [|h1 t1].
  Case "l1 = nil". simpl. rewrite app_nil_end. reflexivity.
  Case "l1 = h1 t1".
    simpl. rewrite snoc_append. rewrite snoc_append.
    rewrite IHt1. rewrite app_ass. reflexivity.
Qed.

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

Lemma nonzeros_app : forall l1 l2 : natlist,
  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).
Proof.
  intros l1 l2. induction l1 as [|h t].
  Case "l1 = nil". reflexivity.
  Case "l2 = h t". simpl. rewrite IHt.
    induction h as [|h'].
    SCase "h = 0". reflexivity.
    SCase "h = S h'". reflexivity.
Qed.
(** [] *)

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

(** **** Exercise: 2 stars (list_design) *)
(** Design exercise:
     - Write down a non-trivial theorem involving [cons]
       ([::]), [snoc], and [app] ([++]).
     - Prove it. *)

Theorem cons_app_cnos_exercise : forall (m n : nat) (ms ns : natlist),
  cons m ms ++ snoc ns n = (cons m (snoc (ms ++ ns) n)).
Proof.
  intros m n ms ns. simpl.
  rewrite snoc_append. rewrite snoc_append.
  rewrite app_ass. reflexivity.
Qed.

(** [] *)

(** **** Exercise: 3 stars, advanced (bag_proofs) *)
(** Here are a couple of little theorems to prove about your
    definitions about bags in the previous problem. *)

Theorem count_member_nonzero : forall (s : bag),
  ble_nat 1 (count 1 (1 :: s)) = true.
Proof.
  intros s. reflexivity.
Qed.

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

Theorem ble_n_Sn : forall n,
  ble_nat n (S n) = true.
Proof.
  intros n. induction n as [| n'].
  Case "0".
    simpl.  reflexivity.
  Case "S n'".
    simpl.  rewrite IHn'.  reflexivity.  Qed.

Theorem remove_decreases_count: forall (s : bag),
  ble_nat (count 0 (remove_one 0 s)) (count 0 s) = true.
Proof.
  intros s. induction s as [|n s'].
  Case "s = nil". reflexivity.
  Case "s = cons n s'". simpl.
    induction n as [|n'].
    SCase "n = 0". simpl. rewrite ble_n_Sn. reflexivity.
    SCase "n = S n'". simpl. rewrite IHs'. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, optional (bag_count_sum) *)
(** Write down an interesting theorem about bags involving the
    functions [count] and [sum], and prove it.*)

Lemma plus_n_0 : forall n : nat,
  n + 0 = n.
Proof.
  intros n. induction n as [|n'].
  Case "n = 0". reflexivity.
  Case "n = S n'". simpl. rewrite IHn'. reflexivity.
Qed.

Theorem count_sum_exercise : forall (n : nat) (xs ys : natlist),
  count n xs + count n ys = count n (sum xs ys).
Proof.
  intros n xs ys.
  induction xs as [|x' xs'].
  Case "xs = nil". reflexivity.
  Case "xs = x' :: xs'". simpl. destruct (beq_nat x' n).
    SCase "x' = n". rewrite <- IHxs'. reflexivity.
    SCase "x' /= n". rewrite IHxs'. 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 solve this exercise.
*)
Theorem rev_inj : forall (l1 l2 : natlist),
  rev l1 = rev l2 -> l1 = l2.
Proof.
  intros l1 l2 H.
  assert (rev (rev l1) = rev (rev l2)).
    rewrite H. reflexivity.
  rewrite <- rev_involutive. rewrite <- H0.
  rewrite rev_involutive. reflexivity.
Qed.
(** [] *)

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

(** Here is another type definition that is often useful in
    day-to-day programming: *)

Inductive natoption : Type :=
  | Some : nat -> natoption
  | None : natoption.

(** One use of [natoption] is as a way of returning "error
    codes" from functions.  For example, 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 return some
    number when the list is too short! *)

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

(** On the other hand, if we give it type [nat -> natlist ->
    natoption], then we can return [None] when the list is too short
    and [Some a] when the list has enough members and [a] appears at
    position [n]. *)

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

Example test_index1 :    index 0 [4;5;6;7]  = Some 4.
Proof. reflexivity.  Qed.
Example test_index2 :    index 3 [4;5;6;7]  = Some 7.
Proof. reflexivity.  Qed.
Example test_index3 :    index 10 [4;5;6;7] = None.
Proof. reflexivity.  Qed.

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

Fixpoint index' (n:nat) (l:natlist) : natoption :=
  match l with
  | nil => None
  | a :: l' => if beq_nat n O then Some a else index' (pred n) l'
  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 allows 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 (hd_opt) *)
(** 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_opt (l : natlist) : natoption :=
  match l with
  | [] => None
  | h :: d => Some h
  end.

Example test_hd_opt1 : hd_opt [] = None.
Proof. reflexivity. Qed.

Example test_hd_opt2 : hd_opt [1] = Some 1.
Proof. reflexivity. Qed.

Example test_hd_opt3 : hd_opt [5;6] = Some 5.
Proof. reflexivity. Qed.
(** [] *)

(** **** Exercise: 1 star, optional (option_elim_hd) *)
(** This exercise relates your new [hd_opt] to the old [hd]. *)

Theorem option_elim_hd : forall (l:natlist) (default:nat),
  hd default l = option_elim default (hd_opt l).
Proof.
  intros l default. induction l as [|n l'].
  Case "l = nil". reflexivity.
  Case "l = cons n l'". reflexivity.
Qed.
(** [] *)

(** **** Exercise: 2 stars (beq_natlist) *)
(** Fill in the definition of [beq_natlist], which compares
    lists of numbers for equality.  Prove that [beq_natlist l l]
    yields [true] for every list [l]. *)

Fixpoint beq_natlist (l1 l2 : natlist) : bool :=
  match l1 with
  | [] => match l2 with
          | [] => true
          | y :: ys => false
          end
  | x :: xs => match l2 with
               | [] => false
               | y :: ys => andb (beq_nat x y) (beq_natlist xs ys)
               end
  end.

Example test_beq_natlist1 :   (beq_natlist nil nil = true).
Proof. reflexivity. Qed.
Example test_beq_natlist2 :   beq_natlist [1;2;3] [1;2;3] = true.
Proof. reflexivity. Qed.
Example test_beq_natlist3 :   beq_natlist [1;2;3] [1;2;4] = false.
Proof. reflexivity. Qed.

Lemma beq_nat_refl : forall (n : nat),
  beq_nat n n = true.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0". reflexivity.
  Case "n = S n'". simpl. rewrite IHn'. reflexivity.
Qed.

Theorem beq_natlist_refl : forall l:natlist,
  true = beq_natlist l l.
Proof.
  intros l. induction l as [| n l'].
  Case "l = nil". reflexivity.
  Case "l = cons n l'". simpl. rewrite <- IHl'.
    rewrite beq_nat_refl. reflexivity.
Qed.
(** [] *)

(* ###################################################### *)
(** * Dictionaries *)

(** As a final illustration of how fundamental data structures
    can be defined in Coq, here is the declaration of a simple
    [dictionary] data type, using numbers for both the keys and the
    values stored under these keys.  (That is, a dictionary represents
    a finite map from numbers to numbers.) *)

Module Dictionary.

Inductive dictionary : Type :=
  | empty  : dictionary
  | record : nat -> nat -> dictionary -> dictionary.

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

Definition insert (key value : nat) (d : dictionary) : dictionary :=
  (record key value d).

(** Here is a function [find] that searches a [dictionary] for a
    given key.  It evaluates evaluates to [None] if the key was not
    found and [Some val] if the key was mapped to [val] in the
    dictionary. If the same key is mapped to multiple values, [find]
    will return the first one it finds. *)

Fixpoint find (key : nat) (d : dictionary) : natoption :=
  match d with
  | empty         => None
  | record k v d' => if (beq_nat key k)
                       then (Some v)
                       else (find key d')
  end.

(** **** Exercise: 1 star (dictionary_invariant1) *)
(** Complete the following proof. *)

Theorem dictionary_invariant1' : forall (d : dictionary) (k v: nat),
  (find k (insert k v d)) = Some v.
Proof.
  intros d k v. simpl. rewrite beq_nat_refl. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 1 star (dictionary_invariant2) *)
(** Complete the following proof. *)

Theorem dictionary_invariant2' : forall (d : dictionary) (m n o: nat),
  beq_nat m n = false -> find m d = find m (insert n o d).
Proof.
  intros d m n o H. simpl. rewrite H. reflexivity.
Qed.
(** [] *)

End Dictionary.

End NatList.

(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)


Require Import Arith.
Require Import Bool.

(**************)
(* Exercise 1 *)
(**************)

(* We first want to prove that our definition of add satisfies commutativity. *)

Fixpoint add n m :=
  match n with 0 => m | S p => add p (S m) end.

Lemma addnS : forall n m, add n (S m) = S (add n m).
  induction n.
  - intros m; simpl.
    auto.
  - intros m; simpl.
    apply IHn.
Qed.

(* Q1. Prove the following two theorems: beware that you will probably need
  addnS. *)

(* Already done during the lecture ? *)
Lemma addn0 : forall n, add n 0 = n.
  induction n.
  - unfold add.
    reflexivity.
  - simpl.
    rewrite <- IHn at 2.
    apply (addnS n 0).
Qed.

Lemma add_comm : forall n m, add n m = add m n.
  induction n.
  - induction m.
    * reflexivity.
    * rewrite -> addn0.
      simpl.
      reflexivity.
  - intro.
    simpl.
    rewrite IHn.
    simpl.
    reflexivity.
Qed.

(* Q2. Now state and prove the associativity of this function. *)

(* Q3. Now state and prove a theorem that expresses that the add function
  returns the same result as the addition available in the loaded libraries
  (given by function plus) *)

(*********************)
(* Exercise 2: lists *)
(*********************)
Require Import List  Bool_nat.
Require Import Coq.omega.Omega.

(* From lecture 2 *)
Class Eq (A : Type) := cmp : A -> A -> bool.

Infix "==" := cmp (at level 70, no associativity).

Instance bool_Eq : Eq nat := beq_nat.
(* beq_nat comes from the Coq library. *)

Fixpoint multiplicity (n : nat)(l : list nat) : nat  :=
  match l with
    nil => 0%nat
  | a :: l' =>
    if n == a then S (multiplicity n l')
    else multiplicity n l'
  end.

Definition is_perm (l l'  : list nat)  :=
  forall n, multiplicity n l = multiplicity n l'.

(* Q4. Show the following theorem :  *)

Lemma multiplicity_app  (x : nat) (l1 l2 : list nat) :
  multiplicity x (l1 ++ l2) = multiplicity x l1 + multiplicity x l2.
  induction l1.
  - simpl.
    reflexivity.
  - simpl.
    destruct (x == a).
    + simpl.
      rewrite IHl1.
      reflexivity.
    + assumption.
Qed.

(* Note : for Q5 and Q6, you will probably have an opportunity
  to use the omega tactic *)

(* Q5. State and prove a theorem that expresses that element counts are
  preserved by reverse. *)

(* Q6. Show the following theorem. *)

Lemma is_perm_transpose x y l1 l2 l3 :
  is_perm (l1 ++ x::l2 ++ y::l3) (l1 ++ y :: l2 ++ x :: l3).
  unfold is_perm.
  intro.
  rewrite! multiplicity_app.
  simpl.
  rewrite! multiplicity_app.
  simpl.
  destruct (n == x), (n == y); try reflexivity; try omega.
Qed.

(* Q7 :  Complete the following lemma using only a reasonning
  on the function rev_app defined in Lecture3.v *)
(* Excerpt from Lectuer3.v - Begin *)
Fixpoint rev_app (A : Type)(l1 l2 : list A) : list A :=
  match l1 with
  | nil => l2
  | a :: tl => rev_app A tl (a :: l2)
  end.

Lemma rev_app_nil : forall A (l1 : list A),
rev_app A l1 nil = rev l1.
Proof.
intros A l1.
assert (Htmp: forall l2, rev_app A l1 l2 = rev l1 ++ l2).
+ induction l1; intros l2.
  * simpl. auto.
  * simpl.
    rewrite app_assoc_reverse.
    simpl.
    apply IHl1.
+ rewrite Htmp.
  rewrite app_nil_r.
  auto.
Qed.
(* Excerpt from Lecture3.v - End *)

Lemma rev_rev_id : forall A (l:list A), rev (rev l) = l.
Proof.
  intros.
  rewrite <- rev_app_nil.
  rewrite <- rev_app_nil.
Admitted.

(* Q8 : What does this function do? *)
Fixpoint mask (A : Type)(m : list bool)(s : list A) {struct m} :=
  match m, s with
  | b :: m', x :: s' => if b then x :: mask A m' s' else mask A m' s'
  | _, _ => nil
  end.

Arguments mask [A] _ _.

(* Q9 Prove that : *)
Lemma mask_cat : forall A m1 (s1 : list A),
    length m1 = length s1 ->
  forall m2 s2, mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.
Admitted.

(**************)
(* Exercise 3 *)
(**************)

(* Define an inductive type formula : Type that represents the *)
(*abstract language of propositional logic without variables:
L = L /\ L | L \/ L | ~L | L_true | L_false
*)

(* Define a function formula_holds of type (formula -> Prop computing the *)
(* Coq formula corresponding to an element of type formula *)

(* Define  a function isT_formula of type (formula -> bool) computing *)
(* the intended truth value of (f : formula) *)

(* prove that is (idT_formula f) evaluates to true, then its *)
(*corresponding Coq formula holds ie.:

Require Import Bool.
Lemma isT_formula_correct : forall f : formula,
   isT_formula f = true <-> formula_holds f.
*)

(**************)
(* Exercise 4 *)
(**************)

(* We use the inductive type defined in the lecture: *)

Inductive natBinTree : Set :=
| Leaf : natBinTree
| Node : nat -> natBinTree -> natBinTree -> natBinTree.

(* Define a function which sums all the values present in the tree.

Define a function is_zero_present : natBinTree -> bool, which tests whether
the value 0 is present or not in the tree.

Prove several simple statements about the fonctions tree_size
and tree_height seen in the lecture

Define a function called mirror that computes the mirror image of a tree.

Prove that a tree and its mirror image have the same height.

Prove that mirror is involutive (ie the mirror image of the mirror image
of the tree is this tree).

It is possible to navigate in a binary tree, given a tree t and
a path like "from the root, go to the left subtree, then
 go to the right subtree, then go to the left subtree, etc. "

Such a path can be easily represented by a list of directions. *)

Inductive direction : Set := L (* go left *) | R (* go right *).

(* Define in Coq a function get_label that takes a tree and some path,
and returns the label at which one arrives following the path
(if any) *)

Fixpoint get_label (path : list direction)(t:natBinTree): option nat:= None.
(* TO DO *)

(* Consider the following function :
*)

Fixpoint zero_present (t: natBinTree) : bool :=
match t with Leaf => false
           | Node n t1 t2 =>  beq_nat n 0 ||
                              zero_present t1 ||
                              zero_present t2
end.
(*
Prove that whenever zero_present t = true, then there exists
some path p such that get_label p t = Some 0

*)

(**************)
(* Exercise 5 *)
(**************)

(* Define the function
split : forall A B : Set, list A * B -> (list A) * (list B)

which transforms a list of pairs into a pair of lists
and the function
combine : forall A B : Set, list A * list B -> list (A * B)
which transforms a pair of lists into a list of pairs.

Write and prove two theorems relating the two functions.
*)


Require Import Arith.
Require Import List ZArith.
Require Import Bool.
(* We first want to prove that our definition of add satisfies commutativity. *)

Fixpoint add n m :=
  match n with 0 => m | S p => add p (S m) end.

Lemma addnS : forall n m, add n (S m) = S (add n m).
induction n.
  intros m; simpl.
  reflexivity.
intros m; simpl.
now apply IHn.
Qed.

(* Q1. Prove the following two theorems: beware that you will probably need
  addnS. *)
Lemma addn0 : forall n, add n 0 = n.
Proof.
induction n;simpl;auto.
rewrite addnS.
rewrite IHn.
trivial.
Qed.

Lemma add_comm : forall n m, add n m = add m n.
Proof.
induction n;simpl.
intros.
rewrite addn0;auto.
intros.
rewrite addnS.
rewrite IHn.
rewrite addnS.
trivial.
Qed.

(* Q2. Now state and prove the associativity of this function. *)
Lemma plus_assoc : forall n m p, add n (add m p)= add (add n m) p.
Proof.

(* Q3. Now state and prove a theorem that expresses that the add function
  returns the same result as the addition available in the loaded libraries
  (given by function plus) *)

(* Note that the theorems about commutativity and associativity could be
  consequences of add_plus. *)

(* Programs about lists.  *)

Fixpoint multiplicity (n : Z)(l : list Z) : nat  :=
  match l with
    nil => 0%nat
  | a :: l' =>
    if Zeq_bool n a then S (multiplicity n l')
    else multiplicity n l'
  end.

Definition is_perm (l l'  : list Z)  :=
  forall n, multiplicity n l = multiplicity n l'.

(* Q4. Show the following theorem :  *)

Lemma multiplicity_app  (x : Z) (l1 l2 : list Z) :
  multiplicity x (l1 ++ l2) = multiplicity x l1 + multiplicity x l2.
Admitted.

(* Q5. State and prove a theorem that expresses that element counts are
  preserved by reverse. *)

(* Q6. Show the following theorem.  You will probably have an occasion
  to use the ring tactic *)

Lemma is_perm_transpose x y l1 l2 l3 :
  is_perm (l1 ++ x::l2 ++ y::l3) (l1 ++ y :: l2 ++ x :: l3).
Admitted.

(* Q5 : What does this function do? *)
Fixpoint mask (A : Type)(m : list bool)(s : list A) {struct m} :=
  match m, s with
  | b :: m', x :: s' => if b then x :: mask A m' s' else mask A m' s'
  | _, _ => nil
  end.

Implicit Arguments mask.

(* Q6 Prove that : *)
Lemma mask_cat A m1 (s1 : list A) :
    length m1 = length s1 ->
  forall m2 s2, mask (m1 ++ m2) (s1 ++ s2) = mask m1 s1 ++ mask m2 s2.
Admitted.


(* Chap 2 Proof by Induction *)
From LF Require Export Basics.

(* Chap 2.1 Proof by Induction *)

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

Theorem minus_diag: forall n,
  minus n n = 0.
Proof.
  intros n.
  induction n.
  - reflexivity.
  - simpl. rewrite -> IHn. reflexivity.
Qed.

(* Exercise basic_induction *)

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.
  - reflexivity.
  - simpl. rewrite -> IHn. reflexivity.
Qed.

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

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

(* Chap 2.2 Proofs Within Proofs *)
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_rearrange: forall n m p q: nat,
  (n + m) + (p + q) = (m + n) + (p + q).
Proof.
  intros n m p q.
  assert (H: n + m = m + n).
  {
    rewrite -> plus_comm.
    reflexivity.
  }
  rewrite -> H.
  reflexivity.
Qed.

(* Chap 2.3 Formal vs. Informal Proof *)
(* Skipped *)

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

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

    Use [assert] to help prove this theorem.  You shouldn't need to
    use induction on [plus_swap].
    After that, prove commutativity of multiplication.  (You will probably
    need to define and prove a separate subsidiary theorem to be used
    in the proof of this one.  You may find that [plus_swap] comes in
    handy.)
*)
Theorem plus_swap: forall n m p : nat,
  n + (m + p) = m + (n + p).
Proof.
  intros n m p.
  rewrite -> plus_assoc.
  rewrite -> plus_assoc.
  assert (n + m = m + n).
  {
    rewrite -> plus_comm.
    reflexivity.
  }
  rewrite -> H.
  reflexivity.
Qed.

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

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

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

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

Theorem leb_refl: forall n: nat,
  true = (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 [].
  - 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.
  intros n.
  reflexivity.
Qed.

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

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

Theorem mult_plus_distr_r: forall n m p: nat,
  (n + m) * p = (n * p) + (m * p).
Proof.
  intros n m p.
  induction n.
  - reflexivity.
  - simpl. rewrite -> IHn. rewrite -> plus_assoc. 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.

(** **** Exercise: 2 stars, standard, optional (eqb_refl)

    Prove the following theorem.  (Putting the [true] on the left-hand
    side of the equality may look odd, but this is how the theorem is
    stated in the Coq standard library, so we follow suit.  Rewriting
    works equally well in either direction, so we will have no problem
    using the theorem no matter which way we state it.) *)
Theorem eqb_refl: forall n: nat,
  true = (n =? n).
Proof.
  intros n.
  induction n.
  - reflexivity.
  - simpl. rewrite IHn. reflexivity.
Qed.

(** **** Exercise: 2 stars, standard, optional (plus_swap')

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

   Use the [replace] tactic to do a proof of [plus_swap'], just like
   [plus_swap] but without needing [assert (n + m = m + n)]. *)
Theorem plus_swap' : forall n m p : nat,
  n + (m + p) = m + (n + p).
Proof.
  intros n m p.
  rewrite -> plus_assoc.
  rewrite -> plus_assoc.
  replace (n + m) with (m + n).
  - reflexivity.
  - rewrite plus_comm. reflexivity.
Qed.
(* Note: just a test, not official prove, so may be a little dump. *)

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

    Recall the [incr] and [bin_to_nat] functions that you
    wrote for the [binary] exercise in the [Basics] chapter.  Prove
    that the following diagram commutes:

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

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

    Before you start working on this exercise, copy the definitions
    from your solution to the [binary] exercise here so that this file
    can be graded on its own.  If you want to change your original
    definitions to make the property easier to prove, feel free to
    do so! *)
Theorem bin_to_nat_pres_incr: forall n: bin,
  bin_to_nat (incr n) = S (bin_to_nat n).
Proof.
  intros n.
  induction n.
  - reflexivity.
  - simpl. reflexivity.
  - simpl. rewrite <- plus_n_O. rewrite <- plus_n_O.
    rewrite -> plus_n_Sm.
    rewrite -> plus_n_Sm.
    rewrite -> IHn.
    assert (H: forall t: nat, S t + S t = t + S (S t)).
    {
      intros t.
      destruct t.
      - reflexivity.
      - simpl. rewrite -> plus_n_Sm. reflexivity.
    }
    rewrite -> H.
    reflexivity.
Qed.

(** **** Exercise: 5 stars, advanced (binary_inverse)

    This is a further continuation of the previous exercises about
    binary numbers.  You may find you need to go back and change your
    earlier definitions to get things to work here.

    (a) First, write a function to convert natural numbers to binary
        numbers. Prove that, if we start with any [nat], convert it to
        binary, and convert it back, we get the same [nat] we started
        with.  (Hint: If your definition of [nat_to_bin] involved any
        extra functions, you may need to prove a subsidiary lemma showing
        how such functions relate to [nat_to_bin].)
    (b) One might naturally expect that we should also prove the
        opposite direction -- that starting with a binary number,
        converting to a natural, and then back to binary should yield
        the same number we started with.  However, this is not the
        case!  Explain (in a comment) what the problem is.
    (c) Define a normalization function -- i.e., a function
        [normalize] going directly from [bin] to [bin] (i.e., _not_ by
        converting to [nat] and back) such that, for any binary number
        [b], converting [b] to a natural and then back to binary yields
        [(normalize b)].  Prove it.  (Warning: This part is a bit
        tricky -- you may end up defining several auxiliary lemmas.
        One good way to find out what you need is to start by trying
        to prove the main statement, see where you get stuck, and see
        if you can find a lemma -- perhaps requiring its own inductive
        proof -- that will allow the main proof to make progress.) Don't
        define thi using nat_to_bin and bin_to_nat!
*)

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

Theorem nat_bin_nat: forall n: nat, 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.

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

Compute normalize (A (B (A (A Z)))).

Lemma normalize_incr_comm: forall b: bin, normalize (incr b) = incr (normalize b).
Proof.
  intros b.
  induction b.
  - reflexivity.
  - simpl.
    destruct (normalize b).
    + simpl. reflexivity.
    + simpl. reflexivity.
    + simpl. reflexivity.
  - simpl.
    rewrite -> IHb.
    destruct (normalize b).
    + simpl. reflexivity.
    + simpl. reflexivity.
    + simpl. reflexivity.
Qed.

Lemma twice_is_A: forall n: nat, nat_to_bin(n + n) = normalize (A (nat_to_bin n)).
Proof.
  intros n.
  induction n.
  - simpl. reflexivity.
  - replace (nat_to_bin (S n + S n)) with (incr (incr (nat_to_bin (n + n)))).
    rewrite IHn.
    rewrite <- normalize_incr_comm.
    rewrite <- normalize_incr_comm.
    reflexivity.
    simpl.
    rewrite <- plus_n_Sm.
    simpl.
    reflexivity.
Qed.

Lemma normalize_twice_eq_normalize: forall b: bin, normalize (normalize b) = normalize b.
Proof.
  intros b.
  induction b.
  - reflexivity.
  - simpl.
    destruct (normalize b).
    + reflexivity.
    + replace (normalize (A (A b0))) with (
        match normalize (A b0) with
        | Z => Z
        | A c => A (A c)
        | B c => A (B c)
        end
      ).
      rewrite -> IHb.
      reflexivity.
      simpl. reflexivity.
    + simpl. rewrite <- IHb. simpl. reflexivity.
  - simpl. rewrite IHb. reflexivity.
Qed.

Theorem normalize_eq_bin_nat_bin: forall b: bin, normalize b = nat_to_bin (bin_to_nat b).
Proof.
  intros b.
  induction b.
  - reflexivity.
  - simpl.
    rewrite <- plus_n_O.
    rewrite -> twice_is_A.
    simpl. rewrite <- IHb.
    rewrite -> normalize_twice_eq_normalize.
    reflexivity.
  - simpl. rewrite -> IHb.
    rewrite <- plus_n_O.
    rewrite -> twice_is_A.
    rewrite <- IHb.
    simpl.
    rewrite -> normalize_twice_eq_normalize.
    destruct (normalize b).
    + reflexivity.
    + reflexivity.
    + reflexivity.
Qed.


From mathcomp
Require Import ssreflect ssrbool ssrnat eqtype seq.

Module FunProg.

(**
---------------------------------------------------------------------
Exercise [Power of two]
---------------------------------------------------------------------
Write the function [two_power] of type [nat -> nat], such that
[two_power n = 2^n]. Use the functions that we have defined earlier.
*)

Fixpoint two_power n := match n with
  | 0 => 1
  | m.+1 => 2 * (two_power m)
  end.

(**
---------------------------------------------------------------------
Exercise [Even numbers]
---------------------------------------------------------------------

Define the function [evenB] of type [nat -> bool], such that it
returns [true] for even numbers and [false] otherwise. Use the
function we have already defined.
*)

Fixpoint evenB n := if n is m.+1 then ~~ (evenB m) else true.

(**
---------------------------------------------------------------------
Exercise [Division by 4]
---------------------------------------------------------------------

Define the function [div4] that maps any natural number [n] to the
integer part of [n/4].
*)

Fixpoint div4 n := if n is m.+4 then (div4 m).+1 else 0.

(**
---------------------------------------------------------------------
Exercise [Representing rational numbers]
---------------------------------------------------------------------

Every strictly positive rational number can be obtained in aunique
manned by a succession of applications of functions [N] nad [D] on the
number one, where [N] and [D] defined as follows:

[[
N(x) = 1 + x

D(x) = 1/(1 + 1/x)
]]

Define an inductive type (with three constructors), such that it
uniquely defines strictly positive rational using the representation
above.

Then, define the function that takes an element of the defined type
nad returns a numerator and denominator of the corresponding fraction.
*)

Inductive rational : Set :=
 One | N of rational | D of rational.

Fixpoint rat_to_frac (r: rational) : nat * nat :=
  match r with
  | One => (1, 1)
  | N x => let: (a, b) := rat_to_frac x
           in (b + a, b)
  | D x => let (a, b) := rat_to_frac x
           in (a, a + b)
  end.

(**
---------------------------------------------------------------------
Exercise [Infinitely-branching trees]
---------------------------------------------------------------------

Define an inductive type of infinitely-branching trees (parametrized
over a type [T]), whose leafs are represented by a constructor that
doesn't take parameters and a non-leaf nodes contain a value _and_ a
function that takes a natural number and returns a child of the node
with a corresponding natural index.

Define a boolean function that takes such a tree (instantiated with a
type [nat]) and an argument of [n] type [nat] and checks whether the
zero value occurs in it at a node reachable only by indices smaller
than a number [n]. Then write some "test-cases" for the defined
function.

Hint: You might need to define a couple of auxiliary functions for
this exercise.

Hint: Sometimes you might need to provide the type arguments to
constructors explicitly.

*)

Inductive inf_tree {T: Set} := Leaf | Node of T & (nat -> @inf_tree T).

Fixpoint check_subtrees (checker: nat -> bool) n :=
  if n is m.+1
  then checker n || check_subtrees checker m
  else checker 0.

Fixpoint has_zero (t: @inf_tree nat) n {struct t} : bool :=
  match t with
  | Leaf => false
  | Node x f => (x == 0) ||
                check_subtrees (fun s => has_zero (f s) n) n
  end.

Eval compute in
  has_zero (Node 2 (fun x => if x == 3 then Node 0 (fun x => Leaf) else Leaf)) 3.

(**
---------------------------------------------------------------------
Exercise [List-find]
---------------------------------------------------------------------

Write a function that take a type [A], a function [f] of type [A ->
bool] and a list [l], and return the first element [x] in [l], such
that [f x == true].

%\hint% Use Coq's [option] type to account for the fact that the
 function of interest is partially-defined.
*)

Fixpoint first_elt A (f: A -> bool) (l : seq A) : option A :=
  if l is x::xs
  then if f x then Some x else first_elt A f xs
  else None.

(**
---------------------------------------------------------------------
Exercise [Generate a range]
---------------------------------------------------------------------

Implement a function that takes a number [n] and returns the list
containing the natural numbers from [1] to [n], _in this order_.
*)

Fixpoint nns n z :=
  if n is m.+1
  then z :: (nns m (z.+1))
  else [::].

Definition Nns n := nns n 1.

(**
---------------------------------------------------------------------
Exercise [Standard list combinators]
---------------------------------------------------------------------

Implement the following higher-order functions on lists

- map
- filter
- fold_left
- fold_right
- tail-recursive list reversal
*)

Fixpoint fold_left {A B} (f: B -> A -> B) z (l: seq A): B :=
  if l is x::xs
  then fold_left f (f z x) xs
  else z.

Eval compute in fold_left (fun x y => x + y) 0 [::1;2;4].

Fixpoint fold_right {A B} (f: A -> B -> B) z (l: seq A): B :=
  if l is x::xs
  then (f x (fold_right f z xs))
  else z.

Eval compute in fold_left (fun x y => x + y) 5 [::1;2;4].

(**
---------------------------------------------------------------------
Exercises [No-stuttering lists]
---------------------------------------------------------------------

We say that a list of numbers "stutters" if it repeats the same number
consecutively. The predicate "nostutter ls" means that ls does not
stutter. Formulate an inductive definition for nostutter. Write some
"unit tests" for this function.

*)

Fixpoint eqn m n {struct m} :=
  match (m, n) with
  | (0, 0) => true
  | (m'.+1, n'.+1) => eqn m' n'
  | (_, _) => false
  end.

Fixpoint nostutter (l : seq nat): bool :=
  if l is x1::xs1
  then if xs1 is x2::xs2 then ~~(eqn x1 x2) && nostutter xs1
                         else true
  else true.

Eval compute in nostutter [:: 1;2;3;4;5].

Eval compute in nostutter [:: 1;2;3;3;4;5].

(**
---------------------------------------------------------------------
Exercise [List alternation]
---------------------------------------------------------------------

Implement the recursive function [alternate] of type [seq nat -> seq
nat -> seq nat], so it would construct the alternation of two
sequences.

%\hint% The reason why the "obvious" elegant solution might fail is
 that the argument is not strictly decreasing.
*)

Fixpoint alternate (l1 l2 : seq nat) : seq nat :=
match (l1, l2) with
  | ([::], ys) => ys
  | (xs, [::]) => xs
  | (x::xs, y::ys) => x :: y :: (alternate xs ys)
  end.

Eval compute in alternate [:: 1;2;3;4;5] [:: 1;2;3;4;6].

(**
---------------------------------------------------------------------
Exercise [Functions with dependently-typed result type]
---------------------------------------------------------------------

Write a function that has a dependent result type and whose result is
[true] for natural numbers of the form [4n + 1], [false] for numbers
of the form [4n + 3] and [n] for numbers of the from [2n].

%\hint% Again, you might need to define a number of auxiliary
 (possibly, higher-order) functions to complete this exercise.
*)

Fixpoint dep_type (n : nat) : Set := match n with
  | 0 => nat
  | 1 => bool
  | n'.+2 => dep_type n'
  end.

Fixpoint dep_value_aux (n: nat): dep_type n -> dep_type n :=
  match n return dep_type n -> dep_type n with
  | 0 => fun x => x.+1
  | 1 => fun x => ~~x
  | n'.+2 => dep_value_aux n'
  end.

Fixpoint dep_value (n: nat): dep_type n :=
  match n  with
  | 0 => 0
  | 1 => true
  | n'.+2 => dep_value_aux n' (dep_value n')
  end.

Eval compute in dep_value 6.

End FunProg.


Require Import Coq.Bool.Bool Coq.Arith.PeanoNat.

Class Monoid {A : Type} (empty : A) (append : A -> A -> A):=
  {
    associativity : forall (x y z : A),
        append x (append y z) = append (append x y) z;

    l_neutral : forall (x : A), append empty x = x;
    r_neutral : forall (x : A), append x empty = x;
  }.

Instance BoolMonoidOr : Monoid false orb :=
  {}.
  (* associativity *)
  Proof.
    intros. apply orb_assoc.
  (* l_neutral *)
  Proof.
    intros. apply orb_false_l.
  (* r_neutral *)
  Proof.
    intros. apply orb_false_r.
  Defined.

Instance BoolMonoidAnd : Monoid true andb :=
  {}.
  (* associativity *)
  Proof.
    intros. apply andb_assoc.
  (* l_neutral *)
  Proof.
    intros. apply andb_true_l.
  (* r_neutral *)
  Proof.
    intros. apply andb_true_r.
  Defined.

Instance NatMonoidPlus : Monoid 0 Nat.add :=
  {}.
  (* associativity *)
  Proof.
    intros. apply Nat.add_assoc.
  (* l_neutral *)
  Proof.
    intros. apply Nat.add_0_l.
  (* r_neutral *)
  Proof.
    intros. apply Nat.add_0_r.
  Defined.

Instance NatMonoidMul : Monoid 1 Nat.mul :=
  {}.
  (* associativity *)
  Proof.
    intros. apply Nat.mul_assoc.
  (* l_neutral *)
  Proof.
    intros. apply Nat.mul_1_l.
  (* r_neutral *)
  Proof.
    intros. apply Nat.mul_1_r.
  Defined.


(** * MoreProp: More about Propositions and Evidence *)

Require Export "Prop".

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

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

Module LeModule.

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

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

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

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

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

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

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

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

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

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

End LeModule.

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

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

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

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

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

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

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

Inductive total_relation : nat -> nat -> Prop :=
  t : forall n m, total_relation n m.
(** [] *)

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

Inductive empty_relation : nat -> nat -> Prop :=
  e : forall n m, 2 + 2 = 5 -> empty_relation n m.
(** [] *)

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

Theorem Sn_le_m__n_le_m : forall n m,
  S n <= m -> n <= m.
Proof.
  intros n m H. induction H.
  Case "le_n". apply le_S. apply le_n.
  Case "le_S". apply le_S. apply IHle.  Qed.

Lemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.
Proof.
  intros m n o H1 H2. induction H1 as [| n'].
  Case "le_n".
    apply H2.
  Case "le_S".
    apply IHle. apply Sn_le_m__n_le_m in H2. apply H2.  Qed.

Theorem O_le_n : forall n,
  0 <= n.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0". apply le_n.
  Case "n = S n'". apply le_S. apply IHn'.  Qed.

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

Theorem Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
  intros n m H. inversion H.
    apply le_n.
    apply Sn_le_m__n_le_m. apply H1.  Qed.

Theorem le_plus_l : forall a b,
  a <= a + b.
Proof.
  intros a b. induction a as [| a'].
  Case "a = 0". simpl. apply O_le_n.
  Case "a = S a'". simpl. apply n_le_m__Sn_le_Sm. apply IHa'.  Qed.

Theorem plus_lt : forall n1 n2 m,
  n1 + n2 < m ->
  n1 < m /\ n2 < m.
Proof.
  unfold lt. intros n1 n2 m H.
  split.    (* eplained in Logic *)
  Case "left".
    induction n2 as [| n2'].
    SCase "n2 = 0".
      rewrite -> plus_0_r in H. apply H.
    SCase "n2 = S n2'".
      apply IHn2'. apply Sn_le_m__n_le_m.
      rewrite <- plus_n_Sm in H. apply H.
  Case "right".
    induction n1 as [| n1'].
    SCase "n1 = 0".
      simpl in H. apply H.
    SCase "n1 = S n1'".
      apply IHn1'. apply Sn_le_m__n_le_m. apply H.  Qed.

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

Theorem ble_nat_true : forall n m,
  ble_nat n m = true -> n <= m.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    intros m eq. apply O_le_n.
  Case "n = S n'".
    intros m eq. destruct m as [| m'].
    SCase "m = 0".
      inversion eq.
    SCase "m = S m'".
      apply n_le_m__Sn_le_Sm. apply IHn'. inversion eq. reflexivity.  Qed.

Theorem le_ble_nat : forall n m,
  n <= m ->
  ble_nat n m = true.
Proof.
  (* Hint: This may be easiest to prove by induction on [m]. *)
  intros n m. generalize dependent n. induction m as [| m'].
  Case "m = 0".
    intros n eq. inversion eq. reflexivity.
  Case "m = S m'".
    intros n eq. destruct n as [| n'].
    SCase "n = 0".
      reflexivity.
    SCase "n = S n'".
      simpl. apply IHm'. apply Sn_le_Sm__n_le_m. apply eq.  Qed.

Theorem ble_nat_true_trans : forall n m o,
  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.
Proof.
  (* Hint: This theorem can be easily proved without using [induction]. *)
  intros n m o eq1 eq2. apply le_ble_nat.
  apply ble_nat_true in eq1. apply ble_nat_true in eq2.
  apply le_trans with (n:=m). apply eq1. apply eq2.  Qed.

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

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

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

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

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

(* FILL IN HERE *)
[]
*)

(** **** Exercise: 3 stars, optional (R_fact) *)
(** Relation [R] actually encodes a familiar function.  State and prove two
    theorems that formally connects the relation and the function.
    That is, if [R m n o] is true, what can we say about [m],
    [n], and [o], and vice versa?
*)

Theorem R_plus : forall (m n o : nat),
  R m n o -> m + n = o.
Proof.
  intros m n o R. induction R.
  Case "R = c1".
    reflexivity.
  Case "R = c2".
    simpl. rewrite -> IHR. reflexivity.
  Case "R = c3".
    rewrite <- plus_n_Sm. rewrite -> IHR. reflexivity.
  Case "R = c4".
    simpl in IHR. rewrite <- plus_n_Sm in IHR. inversion IHR. reflexivity.
  Case "R = c5".
    rewrite -> plus_comm. apply IHR.  Qed.

Theorem plus_R : forall (m n o: nat),
  m + n = o -> R m n o.
Proof.
  intros m. induction m as [| m'].
  Case "m = 0".
    intros n. induction n as [| n'].
    SCase "n = 0".
      intros o H. simpl in H. rewrite <- H. apply c1.
    SCase "n = S n'".
      intros o H. simpl in H. rewrite <- H.
      apply c3. apply IHn'. reflexivity.
  Case "m = S m'".
    intros n. induction n as [| n'].
    SCase "n = 0".
      intros o H. rewrite -> plus_0_r in H. rewrite <- H.
      apply c2. apply IHm'. rewrite -> plus_0_r. reflexivity.
    SCase "n = S n'".
      intros o H. simpl in H. rewrite <- plus_n_Sm in H. rewrite <- H.
      apply c3. apply IHn'. reflexivity.  Qed.
(** [] *)

End R.

(* ##################################################### *)
(** * Programming with Propositions *)

(** A _proposition_ is a statement expressing a factual claim,
    like "two plus two equals four."  In Coq, propositions are written
    as expressions of type [Prop].  Although we haven't discussed this
    explicitly, we have already seen numerous examples. *)

Check (2 + 2 = 4).
(* ===> 2 + 2 = 4 : Prop *)

Check (ble_nat 3 2 = false).
(* ===> ble_nat 3 2 = false : Prop *)

Check (beautiful 8).
(* ===> beautiful 8 : Prop *)

(** Both provable and unprovable claims are perfectly good
    propositions.  Simply _being_ a proposition is one thing; being
    _provable_ is something else! *)

Check (2 + 2 = 5).
(* ===> 2 + 2 = 5 : Prop *)

Check (beautiful 4).
(* ===> beautiful 4 : Prop *)

(** Both [2 + 2 = 4] and [2 + 2 = 5] are legal expressions
    of type [Prop]. *)

(** We've mainly seen one place that propositions can appear in Coq: in
    [Theorem] (and [Lemma] and [Example]) declarations. *)

Theorem plus_2_2_is_4 :
  2 + 2 = 4.
Proof. reflexivity.  Qed.

(** But they can be used in many other ways.  For example, we have also seen that
    we can give a name to a proposition using a [Definition], just as we have
    given names to expressions of other sorts. *)

Definition plus_fact : Prop  :=  2 + 2 = 4.
Check plus_fact.
(* ===> plus_fact : Prop *)

(** We can later use this name in any situation where a proposition is
    expected -- for example, as the claim in a [Theorem] declaration. *)

Theorem plus_fact_is_true :
  plus_fact.
Proof. reflexivity.  Qed.

(** We've seen several ways of constructing propositions.

       - We can define a new proposition primitively using [Inductive].

       - Given two expressions [e1] and [e2] of the same type, we can
         form the proposition [e1 = e2], which states that their
         values are equal.

       - We can combine propositions using implication and
         quantification. *)

(** We have also seen _parameterized propositions_, such as [even] and
    [beautiful]. *)

Check (even 4).
(* ===> even 4 : Prop *)
Check (even 3).
(* ===> even 3 : Prop *)
Check even.
(* ===> even : nat -> Prop *)

(** The type of [even], i.e., [nat->Prop], can be pronounced in
    three equivalent ways: (1) "[even] is a _function_ from numbers to
    propositions," (2) "[even] is a _family_ of propositions, indexed
    by a number [n]," or (3) "[even] is a _property_ of numbers."  *)

(** Propositions -- including parameterized propositions -- are
    first-class citizens in Coq.  For example, we can define functions
    from numbers to propositions... *)

Definition between (n m o: nat) : Prop :=
  andb (ble_nat n o) (ble_nat o m) = true.

(** ... and then partially apply them: *)

Definition teen : nat->Prop := between 13 19.

(** We can even pass propositions -- including parameterized
    propositions -- as arguments to functions: *)

Definition true_for_zero (P:nat->Prop) : Prop :=
  P 0.

(** Here are two more examples of passing parameterized propositions
    as arguments to a function.

    The first function, [true_for_all_numbers], takes a proposition
    [P] as argument and builds the proposition that [P] is true for
    all natural numbers. *)

Definition true_for_all_numbers (P:nat->Prop) : Prop :=
  forall n, P n.

(** The second, [preserved_by_S], takes [P] and builds the proposition
    that, if [P] is true for some natural number [n'], then it is also
    true by the successor of [n'] -- i.e. that [P] is _preserved by
    successor_: *)

Definition preserved_by_S (P:nat->Prop) : Prop :=
  forall n', P n' -> P (S n').

(** Finally, we can put these ingredients together to define
a proposition stating that induction is valid for natural numbers: *)

Definition natural_number_induction_valid : Prop :=
  forall (P:nat->Prop),
    true_for_zero P ->
    preserved_by_S P ->
    true_for_all_numbers P.

(** **** Exercise: 3 stars (combine_odd_even) *)
(** Complete the definition of the [combine_odd_even] function
    below. It takes as arguments two properties of numbers [Podd] and
    [Peven]. As its result, it should return a new property [P] such
    that [P n] is equivalent to [Podd n] when [n] is odd, and
    equivalent to [Peven n] otherwise. *)
Definition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=
  fun n => if oddb n then Podd n else Peven n.

(** To test your definition, see whether you can prove the following
    facts: *)

Theorem combine_odd_even_intro :
  forall (Podd Peven : nat -> Prop) (n : nat),
    (oddb n = true -> Podd n) ->
    (oddb n = false -> Peven n) ->
    combine_odd_even Podd Peven n.
Proof.
  intros Podd Peven n H1 H2. unfold combine_odd_even.
  destruct (oddb n).
    apply H1. reflexivity.
    apply H2. reflexivity.  Qed.

Theorem combine_odd_even_elim_odd :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = true ->
    Podd n.
Proof.
  intros Podd Peven n H1 H2.
  unfold combine_odd_even in H1.
  rewrite -> H2 in H1. apply H1.  Qed.

Theorem combine_odd_even_elim_even :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = false ->
    Peven n.
Proof.
  intros Podd Peven n H1 H2.
  unfold combine_odd_even in H1.
  rewrite -> H2 in H1. apply H1.  Qed.

(** [] *)

(* ##################################################### *)
(** One more quick digression, for adventurous souls: if we can define
    parameterized propositions using [Definition], then can we also
    define them using [Fixpoint]?  Of course we can!  However, this
    kind of "recursive parameterization" doesn't correspond to
    anything very familiar from everyday mathematics.  The following
    exercise gives a slightly contrived example. *)

(** **** Exercise: 4 stars, optional (true_upto_n__true_everywhere) *)
(** Define a recursive function
    [true_upto_n__true_everywhere] that makes
    [true_upto_n_example] work. *)

Fixpoint true_upto_n__true_everywhere (n : nat) (P : nat -> Prop) : Prop :=
  match n with
  | O => forall m : nat, even m
  | S n' => even n -> true_upto_n__true_everywhere n' P
  end.

Example true_upto_n_example :
    (true_upto_n__true_everywhere 3 (fun n => even n))
  = (even 3 -> even 2 -> even 1 -> forall m : nat, even m).
Proof. reflexivity.  Qed.

(** [] *)

(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)


(*
    standard, recommended (basic_induction)
      Prove the following using induction. You might need previously proven results.
*)

From LF Require Export basics.

Theorem mult_0_r : forall n:nat,
  n * 0 = 0.
Proof.
  intros.
  induction n.
  reflexivity.
  rewrite <- mult_n_O.
  reflexivity.
Qed.

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

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

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

(******************************)

(*
    standard (double_plus)
      Consider the following function, which doubles its argument:

      Fixpoint double (n:nat) :=
        match n with
        | O ⇒ O
        | S n' ⇒ S (S (double n'))
        end.
      Use induction to prove this simple fact about double:
*)

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

(******************************)

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

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

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

(******************************)

(*
    standard, recommended (mult_comm)
      Use assert to help prove this theorem.-
      You shouldn't need to use induction on plus_swap.
*)

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

(* Now prove commutativity of multiplication.
   You will probably want to define and prove a "helper" theorem to be used in-
   the proof of this one. Hint: what is n × (1 + k)?
*)

Theorem mult_1_plus_n : forall m n : nat,
  n * ( S m ) = n + ( n * m )
.
Proof.
  intros.
  induction n.
  reflexivity.
  simpl.
  rewrite -> plus_swap.
  f_equal.
  f_equal.
  assumption.
Qed.

Theorem mult_comm : forall m n : nat,
  m * n = n * m.

Proof.
  intros.
  induction n.
  rewrite <- mult_n_O.
  reflexivity.
  simpl.
  rewrite -> mult_1_plus_n.
  rewrite -> IHn.
  reflexivity.
Qed.

(******************************)

(*  standard, optional (more_exercises)

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

Check leb.

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

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

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

Theorem plus_ble_compat_l : forall n m p : nat,
  n <=? m = true -> (p + n) <=? (p + m) = true.
Proof.
  intros.
  induction p.
  assumption.
  assumption.
Qed.

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

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

Lemma excluded_middle: forall b : bool,
  orb b (negb b) = true.
Proof.
  intros.
  destruct b; reflexivity.
Qed.

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

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

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

(******************************)
(*  standard, recommended (binary_commute)

    Recall the [incr] and [bin_to_nat] functions that you
    wrote for the [binary] exercise in the [Basics] chapter.  Prove
    that the following diagram commutes:

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

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

Lemma S_m_n : forall n m : nat,
  S ( m + n ) = S m + n.
Proof.
  intros.
  induction n;reflexivity.
Qed.

Lemma incr_m_S_nat_m : forall m : bin,
  bin_to_nat m + 1 = S (bin_to_nat m).
Proof.
  intros.
  induction m.
  reflexivity.
  simpl.
  rewrite <- plus_n_O.
  rewrite <- plus_assoc.
  rewrite -> IHm.
  rewrite S_m_n.
  rewrite <- plus_comm.
  reflexivity.
  simpl.
  rewrite <- plus_n_O.
  rewrite -> S_m_n.
  rewrite <- plus_comm.
  reflexivity.
Qed.

Lemma bin_to_nat_pres_incr : forall m : bin,
  bin_to_nat (incr m) = S (bin_to_nat m).
Proof.
  intros m.
  induction m.
  reflexivity.
  simpl.
  rewrite <- plus_n_O.
  rewrite <- plus_assoc.
  rewrite plus_n_Sm.
  rewrite <- incr_m_S_nat_m.
  reflexivity.
  simpl.
  rewrite <- plus_n_O.
  rewrite <- plus_n_O.
  rewrite -> IHm.
  simpl.
  rewrite <- incr_m_S_nat_m.
  simpl.
  rewrite -> S_m_n.
  rewrite -> S_m_n.
  rewrite -> S_m_n.
  rewrite <- plus_assoc.
  reflexivity.
Qed.

(*  advanced (binary_inverse)

    This is a further continuation of the previous exercises about
    binary numbers.  You may find you need to go back and change your
    earlier definitions to get things to work here.

    (a) First, write a function to convert natural numbers to binary
        numbers. *)

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

(** Prove that, if we start with any [nat], convert it to binary, and
    convert it back, we get the same [nat] we started with.  (Hint: If
    your definition of [nat_to_bin] involved any extra functions, you
    may need to prove a subsidiary lemma showing how such functions
    relate to [nat_to_bin].) *)

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

(** (b) One might naturally expect that we should also prove the
        opposite direction -- that starting with a binary number,
        converting to a natural, and then back to binary should yield
        the same number we started with.  However, this is not the
        case!  Explain (in a comment) what the problem is. *)

(**** The defined Binary Representation for each nat is not  unique.
   For example 0 can be represnted as Z, B Z, B B B Z, ... ****)

(** (c) Define a normalization function -- i.e., a function
        [normalize] going directly from [bin] to [bin] (i.e., _not_ by
        converting to [nat] and back) such that, for any binary number
        [b], converting [b] to a natural and then back to binary yields
        [(normalize b)].  Prove it.  (Warning: This part is a bit
        tricky -- you may end up defining several auxiliary lemmas.
        One good way to find out what you need is to start by trying
        to prove the main statement, see where you get stuck, and see
        if you can find a lemma -- perhaps requiring its own inductive
        proof -- that will allow the main proof to make progress.) Don't
        define this using [nat_to_bin] and [bin_to_nat]! *)

(* Double of Z is Z and double of anything else is just itself with another-
   zero in front of it *)
Fixpoint double_bin (b:bin) : bin :=
  match b with
  | Z => Z
  | _ => A b
  end.

(* Normal of Z is Z,
   Normal of anything in form of "n'0" is normal of n' with 0 in front of it-
  (see double_bin definition)
   Normal of anything in form of "n'1" is normal of n' whit 1 in front of it

  This Definition can be rewrite without double, just using B as zero-concatinator
*)
Fixpoint normalize (b:bin) : bin :=
  match b with
  | Z  => Z
  | A b' => double_bin( normalize b')
  | B b' => B (normalize b')
  end.

Lemma double_inc : forall m : bin,
  double_bin ( incr m ) = incr (incr ( double_bin m )).
Proof.
  intros.
  induction m; reflexivity.
Qed.

Lemma double_to_plus : forall n : nat,
  nat_to_bin (n + n) = double_bin (nat_to_bin n).
Proof.
  intros.
  induction n.
  simpl.
  reflexivity.
  simpl.
  rewrite <- plus_n_Sm.
  simpl.
  rewrite -> IHn.
  simpl.
  rewrite double_inc.
  reflexivity.
Qed.

Lemma plus_1_to_inct : forall n : nat,
  nat_to_bin (n + 1) = incr (nat_to_bin n).
Proof.
  intros.
  induction n.
  reflexivity.
  simpl.
  rewrite IHn.
  reflexivity.
Qed.

Lemma incr_double : forall m : bin,
  incr (double_bin m) = B m.
Proof.
  intros.
  induction m;reflexivity.
Qed.

Theorem bin_nat_bin: forall m : bin,
  nat_to_bin (bin_to_nat m) = normalize m.
Proof.
  intros.
  induction m.
  reflexivity.
  simpl.
  rewrite <- plus_n_O.
  rewrite double_to_plus.
  rewrite IHm; reflexivity.
  simpl.
  rewrite <- plus_n_O.
  rewrite plus_1_to_inct.
  rewrite  double_to_plus.
  rewrite IHm.
  rewrite incr_double.
  reflexivity.
Qed.