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

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

Check (pair 3 5).

(** Here are simple functions 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.

Compute (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 pair notation can be used both in expressions and in
    pattern matches (indeed, we've actually seen this already in the
    [Basics] chapter, in the definition of the [minus] function --
    this works because the pair notation is also provided as part of
    the standard library): *)

Compute (fst (3,5)).

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

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

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

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

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

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

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

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

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

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

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

(** **** 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 [n m]. simpl. 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 [n m]. simpl. reflexivity.
Qed.
(** [] *)

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

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

Inductive natlist : Type :=
  | nil  : 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 declarations
    allow us to use [::] as an infix [cons] operator and square
    brackets as an "outfix" notation for constructing lists. *)

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

(** It is not necessary to understand the details of these
    declarations, but 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])].

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

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

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

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

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

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

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

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

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

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

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

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

(* ----------------------------------------------------------------- *)
(** *** Head (with default) and Tail *)

(** Here are two smaller examples of programming with lists.
    The [hd] function returns the first element (the "head") of the
    list, while [tl] returns everything but the first
    element (the "tail").
    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.

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

(** **** Exercise: 2 stars, recommended (list_funs)  *)
(** Complete the definitions of [nonzeros], [oddmembers] and
    [countoddmembers] below. Have a look at the tests to understand
    what these functions should do. *)

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

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

Fixpoint oddmembers (l:natlist) : natlist :=
  match l with
    | nil => nil
    | 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].
Proof. simpl. reflexivity. Qed.

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

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

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

Example test_countoddmembers3:
  countoddmembers nil = 0.
Proof. simpl. 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, l2 with
    | nil, nil => nil
    | x :: x', nil => x :: x'
    | nil, y :: y' => y :: y'
    | x :: x', y :: y' => x :: y :: (alternate x' y')
  end.

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

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

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

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

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

(** A [bag] (or [multiset]) is like a set, except that each element
    can appear multiple times rather than just once.  One possible
    implementation is to represent a bag of numbers as a list. *)

Definition bag := natlist.

(** **** Exercise: 3 stars, recommended (bag_functions)  *)
(** Complete the following definitions for the functions
    [count], [sum], [add], and [member] for bags. *)

Fixpoint count (v:nat) (s:bag) : nat :=
  match v, s with
    | v, nil => O
    | v, s :: s' =>
      match (beq_nat v s) with
        | true => S (count v s')
        | false => (count v s')
      end
  end.

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

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

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

Definition sum : bag -> bag -> bag := (alternate).

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

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

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

Definition member (v:nat) (s:bag) : bool :=
  match (count v s) with
    | O => false
    | S n' => true
  end.

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

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

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

(** When [remove_one] is applied to a bag without the number to remove,
   it should return the same bag unchanged. *)
(*
Fixpoint remove_one (v:nat) (s:bag) : bag
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Example test_remove_one1:
  count 5 (remove_one 5 [2;1;5;4;1]) = 0.
  (* FILL IN HERE *) Admitted.

Example test_remove_one2:
  count 5 (remove_one 5 [2;1;4;1]) = 0.
  (* FILL IN HERE *) Admitted.

Example test_remove_one3:
  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.
  (* FILL IN HERE *) Admitted.

Example test_remove_one4:
  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.
  (* FILL IN HERE *) Admitted.

Fixpoint remove_all (v:nat) (s:bag) : bag
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Example test_remove_all1:  count 5 (remove_all 5 [2;1;5;4;1]) = 0.
 (* FILL IN HERE *) Admitted.
Example test_remove_all2:  count 5 (remove_all 5 [2;1;4;1]) = 0.
 (* FILL IN HERE *) Admitted.
Example test_remove_all3:  count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.
 (* FILL IN HERE *) Admitted.
Example test_remove_all4:  count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.
 (* FILL IN HERE *) Admitted.

Fixpoint subset (s1:bag) (s2:bag) : bool
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Example test_subset1:              subset [1;2] [2;1;4;1] = true.
 (* FILL IN HERE *) Admitted.
Example test_subset2:              subset [1;2;2] [2;1;4;1] = false.
 (* FILL IN HERE *) Admitted.
*)
(* Do not modify the following line: *)
Definition manual_grade_for_bag_theorem : option (prod nat string) := None.
(** [] *)

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

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

(** [] *)

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

(** 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
    "scrutinee" (the expression whose value is being "scrutinized" by
    the match) in the definition of [app], allowing the match itself
    to be simplified. *)

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

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

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

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

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

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

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

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

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

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

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

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

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

(** Notice that, as when doing induction on natural numbers, the
    [as...] clause provided to the [induction] tactic gives a name to
    the induction hypothesis corresponding to the smaller list [l1']
    in the [cons] case. Once again, this Coq proof is not especially
    illuminating as a static 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. *)

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

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

   _Proof_: By induction on [l1].

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

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

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

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

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

     (the induction hypothesis). We must show

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

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

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

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

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

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

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

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

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

(** Now let's prove some theorems about our newly defined [rev].
    For something a bit more challenging than what we've seen, let's
    prove that reversing a list does not change its length.  Our first
    attempt gets stuck in the successor case... *)

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

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

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

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

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

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

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

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

    _Proof_: By induction on [l1].

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

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

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

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

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

      We must show

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

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

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

    _Proof_: By induction on [l].

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

          length (rev []) = length [],

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

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

          length (rev l') = length l'.

        We must show

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

        By the definition of [rev], this follows from

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

        which, by the previous lemma, is the same as

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

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

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

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

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

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

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

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

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

(*  Search rev. *)

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

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

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

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

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

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

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

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

Theorem app_assoc4 : forall l1 l2 l3 l4 : natlist,
  l1 ++ (l2 ++ (l3 ++ l4)) = ((l1 ++ l2) ++ l3) ++ l4.
Proof.
  intros l1 l2 l3 l4. rewrite app_assoc. rewrite app_assoc. 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 [| n l' IHl'].
  - simpl. reflexivity.
  - simpl. rewrite IHl'. destruct n.
    + reflexivity.
    + simpl. 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, l2 with
  | nil, nil => true
  | x :: x', nil => false
  | nil, y :: y' => false
  | x :: x', y :: y' =>
    match (beq_nat x y) with
      | true => (beq_natlist x' y')
      | false => false
    end
  end.

Example test_beq_natlist1 :
  (beq_natlist nil nil = true).
Proof. simpl. reflexivity. Qed.

Example test_beq_natlist2 :
  beq_natlist [1;2;3] [1;2;3] = true.
Proof. simpl. reflexivity. Qed.

Example test_beq_natlist3 :
  beq_natlist [1;2;3] [1;2;4] = false.
Proof. simpl. reflexivity. Qed.

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

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

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

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

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

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

(** **** Exercise: 3 stars, advanced (remove_does_not_increase_count)  *)
(*Theorem remove_does_not_increase_count: forall (s : bag),
  leb (count 0 (remove_one 0 s)) (count 0 s) = true.
Proof.
  intros s. induction s as [| n' s' IHs'].
  - simpl.
(** [] *)*)

(** **** Exercise: 3 stars, optional (bag_count_sum)  *)
(** Write down an interesting theorem [bag_count_sum] about bags
    involving the functions [count] and [sum], and prove it using
    Coq.  (You may find that the difficulty of the proof depends on
    how you defined [count]!) *)
(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 4 stars, advanced (rev_injective)  *)
(** Prove that the [rev] function is injective -- that is,

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

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

(* FILL IN HERE *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Definition hd_error (l : natlist) : natoption
  (* REPLACE THIS LINE WITH ":= _your_definition_ ." *). Admitted.

Example test_hd_error1 : hd_error [] = None.
 (* FILL IN HERE *) Admitted.

Example test_hd_error2 : hd_error [1] = Some 1.
 (* FILL IN HERE *) Admitted.

Example test_hd_error3 : hd_error [5;6] = Some 5.
 (* FILL IN HERE *) Admitted.
(** [] *)

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

Theorem option_elim_hd : forall (l:natlist) (default:nat),
  hd default l = option_elim default (hd_error l).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

End NatList.

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

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

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

Inductive id : Type :=
  | Id : nat -> id.

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

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

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

(** **** Exercise: 1 star (beq_id_refl)  *)
Theorem beq_id_refl : forall x, true = beq_id x x.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

Module PartialMap.
Export NatList.

Inductive partial_map : Type :=
  | empty  : partial_map
  | record : id -> nat -> partial_map -> partial_map.

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

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

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

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

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

(** **** Exercise: 1 star (update_eq)  *)
Theorem update_eq :
  forall (d : partial_map) (x : id) (v: nat),
    find x (update d x v) = Some v.
Proof.
 (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star (update_neq)  *)
Theorem update_neq :
  forall (d : partial_map) (x y : id) (o: nat),
    beq_id x y = false -> find x (update d y o) = find x d.
Proof.
 (* FILL IN HERE *) Admitted.
(** [] *)
End PartialMap.

(** **** Exercise: 2 stars (baz_num_elts)  *)
(** Consider the following inductive definition: *)

Inductive baz : Type :=
  | Baz1 : baz -> baz
  | Baz2 : baz -> bool -> baz.

(** How _many_ elements does the type [baz] have?
    (Explain your answer in words, preferrably English.) *)

(* FILL IN HERE *)

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


From mathcomp
Require Import ssreflect ssrfun eqtype ssrnat ssrbool.
Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

Inductive my_eq (A : Type) (x : A) : A -> Prop :=  my_eq_refl : my_eq x x.
Notation "x === y" := (my_eq x y) (at level 70).

Lemma my_eq_sym A (x y: A) : x === y -> y === x.
Proof. by case. Qed.

Lemma disaster : 2 === 1 -> False.
Proof.
move=> H.
pose D x := if x is 2 then False else True.
have D1: D 1 by [].
by case: H D1.
Qed.

(**
---------------------------------------------------------------------
Exercise [Discriminating [===]]
---------------------------------------------------------------------
Let us change the statement of a lemma [disaster] for a little bit:
*)

Lemma disaster2 : 1 === 2 -> False.

(**
Now, try to prove it using the same scheme. What goes wrong and how to
fix it?
*)
Proof.
(* by move=>H; move/disaster: (my_eq_sym H). *)
Proof.
move=> H.
pose D x := if x is 1 then False else True.
have D2: D 2.
by [].
by case: H D2=> /=.
Qed.

(**
---------------------------------------------------------------------
Exercise [Fun with rewritings]
---------------------------------------------------------------------
Prove the following lemma by using the [rewrite] tactics.

*)

Lemma rewrite_is_fun T (f : T -> T -> T) (a b c : T):
  commutative f -> associative f ->
  f (f b a) c = f a (f c b).
Proof.
move=> H1 H2.
by rewrite [(f b a)]H1 -H2 [(f c b)]H1.
Qed.

(**
---------------------------------------------------------------------
Exercise [Properties of maxn]
---------------------------------------------------------------------
Prove the following lemmas about [maxn].
*)

Lemma max_l m n: n <= m -> maxn m n = m.
Proof.
rewrite /maxn.
by case: (leqP n m)=>//.
Qed.

Lemma succ_max_distr_r n m : (maxn n m).+1 = maxn (n.+1) (m.+1).
Proof.
rewrite /maxn.
case: leqP=>//H; case:leqP=>//.
- by rewrite -[n.+1]addn1 -[m.+1]addn1 ltn_add2r ltnNge H.
by rewrite ltnS leqNgt H.
Qed.

Lemma plus_max_distr_l m n p: maxn (p + n) (p + m) = p + maxn n m.
Proof.
rewrite /maxn.
case: leqP=>// H1; case: leqP=>//.
- suff: m <= n by rewrite ltnNge=>H; move/negP.
  by rewrite leq_add2l in H1.
suff: n < m by move=>H; rewrite leqNgt H.
by rewrite ltn_add2l in H1.
Qed.

(**

Hint: it might be useful to employ the lemmas [ltnNge], [leqNgt],
[ltnS] and similar to them from SSReflect's [ssrnat] module. Use the
[Search] command to find propositions that might help you to deal with
the goal.

Hint: Forward-style reasoning via [suff] and [have] might be more
intuitive.

Hint: A hypothesis of the shape [H: n < m] is a syntactic sugar for
[H: n < m = true], since [n < m] in fact has type [bool], as will be
explained in the next lecture.

*)

(**
---------------------------------------------------------------------
Exercise [More custom rewriting rules]
---------------------------------------------------------------------

Let us consider an instance of a more sophisticated custom rewriting
rule, which now encodes a three-variant truth table for the ordering
relations on natural numbers.

*)

Inductive nat_rels m n : bool -> bool -> bool -> Set :=
  | CompareNatLt of m < n : nat_rels m n true false false
  | CompareNatGt of m > n : nat_rels m n false true false
  | CompareNatEq of m = n : nat_rels m n false false true.

(**

The following rewriting lemma establishes a truth table for
[nat_rels]. Step through the proofs (splitting the combined tactics
whenever it's necessary) to see what's going on.

*)

Lemma natrelP m n : nat_rels m n (m < n) (n < m) (m == n).
Proof.
rewrite ltn_neqAle eqn_leq; case: ltnP; first by constructor.
by rewrite leq_eqVlt orbC; case: leqP; constructor; first exact/eqnP.
Qed.

(**
Let us define the minimum function [minn] on natural numbers as
follows:
*)

Definition minn m n := if m < n then m else n.

(**
Prove the following lemma about [minm] and [maxn]:
*)

Lemma addn_min_max m n : minn m n + maxn m n = m + n.
Proof.
rewrite /minn /maxn; by case: natrelP=>//; rewrite addnC.
Qed.


(* Proof by Induction *)

(* The following proof works, but the one after does not *)
Theorem  plus_left_side: forall n : nat, 0 + n = n.
Proof. intros n. simpl. reflexivity. Qed.

Theorem plus_n_O_firsttry : forall n : nat,
  n = n + 0.
Proof. intros n. simpl. (* Does nothing! *) Abort.

Theorem plus_n_O_secondtry : forall n:nat,
  n = n + 0.
Proof. intros n. destruct n as [| n'].
  - (* n = 0 *)
    reflexivity. (* So far so good *)
  - (* n = S n' *)
    simpl. (*... but here we are stuck again *)
  Abort.

(*
Here is the principle of induction over natural numbers:
If P(n) is some proposition involving a natural number n
and we want to show that P holds for all numbers n, we can
reason like this:
  > show that P(O) holds; show that, for any n', if P(n')
  > holds, then so does P(S n'); conclude that P(n) holds
  > for all n.

*)

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

(*
The previous Theorem and proof written on paper

Theorem : For any n,
  n = n + 0

Proof : By induction on n.
  First, suppose n = 0. We must show
    0 = 0 + 0

    This follows directly from the definition of +

  Next, suppose n = S n', where (as our IH)
    n' = n' + 0

    We must show
      S n' = (S n') + 0

      which is immediate from the induction hypothesis.
  Qed.

*)

Theorem minus_diag : forall n, minus n n = 0.
Proof. intros n. induction n as [| n' IHn'].
  - (* n = 0 *)
    simpl. reflexivity.
  - (* n = S n' *)
    simpl. rewrite -> IHn'. reflexivity. Qed.
(*
When applied to a goal that contains quantified variables,
the induction tactic will automatically move them into the
context as needed.
*)

(* Exercise 1 *)
Theorem mult_0_r : forall n : nat,
  n * 0 = 0.
Proof. induction n as [|n' IHn'].
  - reflexivity.
  -simpl. rewrite -> IHn'. reflexivity. Qed.

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

(* My weird attempts
Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof. intros n m. induction n as [|n' IHn'].
  - simpl. induction m as [|m' IHm'].
    + reflexivity.
    + simpl. rewrite <- IHm'. reflexivity.
  - simpl. induction m as [|m' IHm'].
    + rewrite -> IHn'. simpl. reflexivity.
    + rewrite -> IHn'. simpl. rewrite <- IHm'.
      * simpl. rewrite <- IHn'.

rewrite <- IHm'.
     -- rewrite -> IHn'. simpl. reflexivity. rewrite <- IHn'.

    + simpl. rewrite -> IHn'. rewrite <- IHm'. simpl. rewrite <- IHn'.

*)

Theorem plus_comm : forall n m : nat,
  n + m = m + n.

Proof. intros n m. induction n as [|n' IHn'].
  - simpl. rewrite <- plus_N_O. reflexivity.
  - simpl. rewrite -> IHn'. rewrite -> plus_n_Sm. reflexivity.
Qed.

Theorem plus_assoc : forall n m p : nat,
  n + (m + p) = (n + m) + p.

Proof. intros n m p. induction n.
  - simpl. reflexivity.
  - simpl. rewrite -> IHn. reflexivity.
Qed.

(* Proofs within proofs *)


Require Import ZArith.

Require Import List.

Require Extraction.

Set Implicit Arguments.

Extraction Language Haskell.

(************************
**** Exercício 1.
************************)

(**** (a) ****)

Inductive mkList (A:Type) : nat -> A -> (list A) -> Prop :=
  | mkNil : forall (a:A), mkList 0 a nil
  | mkSec : forall (n:nat) (a:A) (l:list A), mkList n a l -> mkList (S n) a (a::l).

Theorem mkList_correct : forall (A:Type) (n:nat) (x:A), { l:list A | mkList n x l }.
Proof.
  intros.
  induction n.
  - exists nil. constructor.
  - destruct IHn. exists (x::x0). constructor. assumption.
Qed.

(* Extração do código *)
Recursive Extraction mkList_correct.

(**** (b) ****)

Inductive pairSum : list (nat*nat) -> list nat -> Prop :=
  | sumNil : pairSum nil nil
  | sumSec : forall (p: (nat*nat)) (inp: list (nat*nat)) (res: list nat), pairSum inp res -> pairSum (p::inp) (((fst p)+(snd p))::res).

Theorem pairSum_correct : forall (inp: list(nat*nat)), {res: list nat | pairSum inp res}.
Proof.
  intros.
  induction inp.
  - exists nil. constructor.
  - elim IHinp.
    + intros. exists ( ((fst a) + (snd a))::x ). constructor. assumption.
Qed.

(* Extração do código *)
Recursive Extraction pairSum_correct.

(************************
**** Exercício 2.
************************)
Open Scope Z_scope.

Fixpoint count (z:Z) (l:list Z) {struct l} : nat :=
  match l with
  | nil => 0%nat
  | (z' :: l') => if (Z.eq_dec z z')
                  then S (count z l')
                  else count z l'
  end.

(**** (a) ****)
Lemma count_corr : forall (x:Z) (a:Z) (l:list Z), x <> a ->  count x (a :: l) = count x l.
Proof.
  intros.
  simpl.
  elim (Z.eq_dec x a).
  - intros. contradiction.
  - intros. trivial.
Qed.

(**** (b) ****)
Inductive countRel : Z -> list Z -> nat -> Prop :=
  | countNil : forall e:Z, countRel e nil 0
  | countIf : forall (e:Z) (l: list Z) (n: nat), countRel e l n -> countRel e (e::l) (S n)
  | countElse : forall (e e':Z) (l: list Z) (n: nat), e <> e' -> countRel e l n -> countRel e (e'::l) n.

(**** (c) ****)
Lemma count_correct : forall (x:Z) (l:list Z), countRel x l (count x l).
Proof.
  intros.
  induction l.
  - simpl. constructor.
  - simpl. elim (Z.eq_dec x a).
    + intros. rewrite <- a0. constructor. assumption.
    + intros. destruct IHl.
      * constructor.
        -- assumption.
        -- constructor.
      * constructor.
        -- assumption.
        -- constructor. assumption.
      * constructor.
        -- assumption.
        -- constructor.
          ++ assumption.
          ++ assumption.
Qed.

Close Scope Z_scope.
(************************************************************* END *************************************************************)


Require Export ProofObjects.

(* ================================================================ *)

(** * O operador "fix" *)

(**
O operador [fix] está para [Fixpoint] assim como [fun] está para
[Definition], ou seja, [fix] serve para definir e usar localmente uma
função recursiva, sem registrar no contexto um nome para ela.

A notação é

  fix nome_local_da_função (argumentos...) : tipo_de_retorno := corpo

como ilustrado abaixo:
*)

Compute
  (
  fix last (l : list nat) : option nat
    :=
    match l with
    | [] => None
    | h1::t1 => match t1 with
                | [] => Some h1
                | h2::t2 => last t1
                end
    end
  )
  [1; 2; 3; 4; 5].

Fail Check last. (** Observe: [last] não está "registrada". *)

(* ================================================================ *)

(** * Provando Teoremas via [fix] *)

(**
Recapitule primeiramente que

  "Coq treats as "the same" any two terms that are _convertible_
   according to a simple set of computation rules. These rules, which
   are similar to those used by [Compute], include evaluation of
   function application, inlining of definitions, and simplification
   of [match]es."

Por exemplo:
*)

(**
Agora, recapitule o argumento deste teorema:  [forall n, n + 0 = n].

  ... (Explicado em sala)

Isso pode ser formalizado diretamente por uma função recursiva:
*)

Check f_equal.

Definition plus_0_r_po: forall n, n + 0 = n
  :=
  fix f (n : nat) : n + 0 = n
    :=
    match n with
    | O => @eq_refl nat 0 : 0 = 0
           (* Ou simplesmente:  @eq_refl nat 0 *)
           (* Ou simplesmente:  eq_refl *)
    | S n' => f_equal nat nat S (n' + 0) n' (f n')
              (* Ou simplesmente:  f_equal _ _ _ _ _ (f n') *)
    end.

(** EXERCÍCIO: prove por meio de uma função recursiva: *)

Definition plus_assoc_po: forall m n o, m + (n+o) = (m+n) + o :=
  fix f m n o : m + (n + o) = (m + n) + o :=
    match m with
    | O => eq_refl
    | S m' => f_equal _ _ S (m' + (n + o)) (m' + n + o) (f m' n o)
    end.

(* ================================================================ *)

(** * Provando Princípios de Indução de Conjuntos via [fix] *)

(**
O mesmo tipo de raciocínio permite provarmos _princípios de indução_
por meio de funções recursivas.

No caso de [nat], por exemplo, temos:
 *)

(* Inductive nat : Type :=
   | O : nat
   | S : nat -> nat *)

Definition nat_ind_po :
  forall P : nat -> Prop,
  P O ->
  ( forall x, P x -> P (S x) ) ->
  forall n : nat, P n
    :=
    fun P p0 ps  (* Essa função adicional recebe os argumentos
                    que não mudam durante as chamadas recursivas *)
      =>
      fix f n : P n
        :=
        match n with
        | O => p0
        | S n' => ( ps n' (f n') ) : P (S n')
                  (* Ou simplesmente:  ( ps n' (f n') ) *)
        end.

(** EXERCÍCIO: defina um tipo [listbool] e enuncie e prove um
    princípio de indução para ele: *)

Inductive listbool : Type :=
  | bnil : listbool
  | bcons : bool -> listbool -> listbool.

Check listbool_ind.

Definition listbool_ind_po :
  forall P : listbool -> Prop,
       P bnil ->
       (forall (b : bool) (l : listbool), P l -> P (bcons b l)) ->
       forall l : listbool, P l :=
  fun P pn pc =>
    fix f l : P l :=
    match l with
    | bnil => pn
    | bcons b l' => pc b l' (f l')
    end.

(** EXERCÍCIO: Enuncie e prove o princípio de indução para [list].
               (Observe que, ao fazê-lo, você estará provando um
    princípio de indução para um tipo polimórfico, mas a ideia não
    muda.) *)

Definition list_ind_po : forall (X : Type) (P : list X -> Prop),
       P [] ->
       (forall (x : X) (l : list X), P l -> P (x :: l)) ->
       forall l : list X, P l :=
  fun X P pn pc =>
    fix f l : P l :=
    match l with
    | nil => pn
    | cons x l' => pc _ _ (f l')
    end.

Print list.
(** EXERCÍCIO: Defina um tipo polimórfico para árvores binárias, e
    prove o princípio de indução correspondente. *)

Inductive btree (X : Type) : Type :=
  | bempty : btree X
  | bleaf : X -> btree X
  | nbranch : X -> btree X -> btree X -> btree X.

Definition btree_ind_po : forall (X : Type) (P : btree X -> Prop),
  P (bempty X) -> (forall (x : X) , P (bleaf X x)) ->
  (forall (x : X) (l : btree X) (r : btree X), P l -> P r -> P (nbranch X x l r)) ->
  forall b : btree X, P b
  :=
  fun X P pe pl pb =>
    fix f bt : P bt :=
    match bt with
    | bempty => pe
    | bleaf x => pl x
    | nbranch x l' r' => pb x l' r' (f l') (f r')
    end.

(** EXERCÍCIO: Escreva um princípio de indução para [nat] cujo passo
    "vá de 2 em 2", ou seja, de P(n) provamos P(S(S n)).

    Dica: Como fica a base?

    Observação: Numa prova com táticas, e supondo que nat_ind2 é o
    objeto de prova que você escreveu acima, você pode usá-lo assim:

      induction n using nat_ind2. *)

(* ================================================================ *)

(** * Provando Princípios de Indução de IndProp's via [fix] *)

(** EXEMPLO: essencialmente a mesma técnica ilustrada acima nos
             permite provar princípios de indução para proposições
    indutivamente definidas.

    Em geral, porém, nós precisamos de um recurso técnico novo: o
    "casamento de padrão dependente" ("dependent pattern matching"),
    que ainda não foi explicado.

    Para ilustrar, segue abaixo o princípio indutivo para [ev] (o
    recurso técnico novo está no "match ... in ... return ... with",
    mas ele serve apenas para convencer o Coq de que os termos
    retornados têm os tipos corretos, e pode ser ignorado por ora): *)

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

Definition ev_ind_po:
  forall P : nat -> Prop,
  P 0 ->
  (forall n, ev n -> P n -> P (S (S n)) ) ->
  forall n, ev n -> P n
    :=
    fun P p0 ps
      =>
      fix f n pevn : P n
        :=
        match pevn in ev a return P a with
        | ev_0 => p0
        | ev_SS n' evn' (* n = S (S n') *) =>
            ps n' evn' (f n' evn')
        end.

(** Os exercícios abaixo são recomendados, e podem ser feitos usando
    apenas o tipo simples e já conhecido de casamento de padrão. *)

(** EXERCÍCIO: Enuncie e prove o princípio de indução para [and]. *)

(* Inductive and (A B : Prop) : Prop :=  conj : A -> B -> A /\ B . *)
Check and_ind.

Definition and_ind_po: forall A B P : Prop, (A -> B -> P) -> A /\ B -> P :=
  fun A B P  (HABP : A -> B -> P) (H : A /\ B)
  => match H with
     | conj HA HB =>  HABP HA HB
     end.

(** EXERCÍCIO: Enuncie e prove o princípio de indução para [False]. *)

(*  Inductive False : Prop := .  *)

Definition False_ind_po : forall P : Prop, False -> P :=
  fun P f => match f with
             end.

(** EXERCÍCIO: Enuncie e prove o princípio de indução para [True]. *)

(*  Inductive True : Prop :=  I : True .  *)

Definition True_ind_po : forall P : Prop, P -> True -> P :=
  fun P (HP : P) (HT : True) => HP.

(* ================================================================ *)


(*

Script du thème 2 : arithmétique.

*)

Require Import Arith.

Print nat.

Example Zero: 0 = O.
Proof. reflexivity. Qed.

Example Cinq: 5 = S (S (S (S (S O)))).
Proof. reflexivity. Qed.

Definition double (n : nat) : nat := 2 * n.

Example square_2_is_2plus2:
  double 2 = 2 + 2.
Proof.
compute.
reflexivity.
Qed.

Lemma double_plus:
forall n : nat, double n = n + n.
Proof.
destruct n as [| n']. (* raisonnement par cas *)
  - (* cas de base: n=0 *)
    compute.  (* remarque : terme clos *)
    reflexivity.
  - (* cas récursif: n=S n' *)
    unfold double.
    simpl.
    SearchPattern ( S _ = S _ ).
    (* eq_S: forall x y : nat, x = y -> S x = S y *)
    apply eq_S.
    SearchPattern ( ?X + 0 = ?X).
    (* plus_0_r: forall n : nat, n + 0 = n *)
    rewrite plus_0_r.
    reflexivity.
Qed.

Lemma double_plus':
forall n : nat, double n = n + n.
Proof.
intro n.
unfold double.
ring.
Qed.

Check nat_ind.

Lemma plus_0_r':
  forall n : nat, n + 0 = n.
Proof.
intro n.
induction n as [| n'].
  - (* cas n=0 *)
    trivial.
  - (* cas n = S n' *)
    simpl.
    rewrite IHn'.
    reflexivity.
Qed.

Lemma plus_0_r'':
  forall n : nat, n + 0 = n.
Proof.
  auto with arith.
Qed.

(* ** Exercice

La relation naturelle entre les listes et les entiers naturels est bien sûr la notion de longueur de liste.

 *** Question 1

Définir une fonction [longueur] retournant la longueur d'une liste.

*)
Print length.
Require Import List.
Fixpoint longueur {A: Set}(l : list A) : nat :=
  match l with
    | nil => 0
    | (e::l') => S (longueur l')
end.

(**

  *** Question 2

*)

Print length.

(**

Montrer que les deux fonctions [longueur] et [length]
effectuent le même calcul.

*)

Lemma len_long : forall A : Set, forall l : list A,
 length l = longueur l.
Proof.
induction l as [|e l'].
-compute.
 trivial.

-simpl.
inversion IHl'.
trivial.
Qed.

(**

 *** Question 3

Démontrer le lemme suivant :

*)

Lemma length_app:
  forall A : Set, forall l1 l2 : list A,
    length (l1 ++ l2) = (length l1) + (length l2).
Proof.
intros A l1 l2.
induction l1 as [|e l'].
-simpl.
 trivial.

-simpl.
rewrite IHl'.
trivial.

Qed.

(**

 *** Question 4

Montrer que [length (map f l) = length l].

*)
Require Import List.
Lemma id_lenmap_len:
  forall A B : Set, forall l: list A, forall f : A -> B,
   length (map f l) = length l.
Proof.
intros A B l f.
induction l as [|e l'].
-simpl.
 trivial.

-simpl.
 rewrite IHl'.
 trivial.

Qed.

(**

** Exercice

*** Question 1

Définir la fonction [sum] calculant : $\sum_{i=0}^{n} i$.

*)

(*Fixpoint sum_it (n : nat) (a : nat) : nat :=
  match n with
   | 0 => a
   | S m => sum (m) (a + n)
end.*)

Fixpoint sum (n : nat) : nat :=
  match n with
   | 0 => 0
   | S m => n + sum m
end.

(**

  *** Question 2  (un peu plus corsée)

Démontrer le théorème classique de la somme : $2 \times \sum^n_{i=1} = n * (n + 1)$.

*)

Example sum1 : forall n : nat, sum 3 = 6.
Proof.
compute.
reflexivity.
Qed.

Theorem arith_sum :
forall n: nat, 2 * sum n = n * (n + 1).

Proof.
induction n as [| n'].
-simpl.
 trivial.

-simpl.
 SearchRewrite ( _ * S (_) ).
 rewrite mult_succ_r.
 SearchPattern ( S _ = S _ ).
 apply eq_S.
 rewrite <- IHn'.
 ring.
Qed.

(**

 ** Exercice : la factorielle

 *** Question 1

Soit la fonction factorielle sur les entiers naturels.

*)

Fixpoint fact (n:nat) : nat :=
  match n with
    | O => 1
    | S m => fact m * n
  end.

Example fact_5: fact 5 = 120.
Proof.
  compute.
  reflexivity.
Qed.

(**

Définir une version [fact_it] récursive terminale de la factorielle.

*)

Fixpoint fact_it (n:nat) (a:nat) : nat :=
  match n with
    | O => a
    | S m => fact_it m (a * n)
  end.

Example factit_5: fact_it 5 1 = 120.
Proof.
  compute.
  reflexivity.
Qed.

(**

 *** Question 2

Démontrer le lemme suivant :

*)

Lemma fact_it_lemma:
  forall n k:nat, fact_it n k = k * (fact n).
Proof.
intros n.
induction n as [| n'].
-intro k.
 simpl.
 SearchRewrite( _ * 1).
 rewrite mult_1_r.
 reflexivity.

- intro k.
  simpl.
  rewrite IHn'.
  SearchRewrite ( _ * ( _ * _) ).
  rewrite mult_assoc.
  ring.
Qed.

(**

 *** Question 3

En déduire un théorème permettant de relier
 les deux versions de la factorielle.

*)

Theorem eq_fact_factit :
  forall n:nat, fact_it n 1 = fact n.
Proof.
intros n.
induction n as [| n'].

-simpl.
 trivial.

-simpl.
rewrite fact_it_lemma.
ring.
Qed.

(**

  ** Exercice : Fibonacci

  *** Question 1

Définir une fonction [fib] de calcul de la suite
 de Fibonacci.

*)

Fixpoint fib (n:nat) : nat :=
match n with
  | 0 => 1
  | 1 => 1
  | S m => fib (S m) + fib (m)
end.

Example fib_ex: fib 4 = 5.
Proof.
  compute.
  reflexivity.
Qed.

(**

  *** Question 2

Démontrer par cas le lemme suivant :

*)

Lemma fib_plus_2:
  forall n:nat, fib (S (S n)) = fib n + fib (S n).
Proof.
intro n.
induction n as [| n'].

-simpl.
 reflexivity.

-Abort.

(**

 *** Question 3 :

Donner une définition [fib_it] récursive terminale de Fibonacci.

*)

Fixpoint fib_aux (n:nat) (a:nat) (b:nat) : nat :=
    match n with
      | 0 => b
      | S (m) => fib_aux m (b) (a + b)
end.

Definition fib_it (n:nat) : nat := fib_aux n 0 1.

(**

  *** Question 4

Démontrer le théorème suivant :

*)

Theorem fib_it_fib:
  forall n:nat, fib_it n 1 1 = fib n.
Proof.
  (* <<COMPLETER ICI>> *)


(**
* Induction in Coq
*)

Require Import List.
Import ListNotations.

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

(** Recursive functions *)

Fixpoint append {A : Type} (lst1 : list A) (lst2 : list A) :=
  match lst1 with
  | nil => lst2
  | h::t => h :: (append t lst2)
  end.

Theorem nil_app : forall (A:Type) (lst : list A),
  [] ++ lst = lst.
Proof.
  intros A lst.
  simpl.
  trivial.
Qed.

Theorem app_nil : forall (A:Type) (lst : list A),
  lst ++ [] = lst.
Proof.
  intros A lst.
  simpl. (* cannot simplify *)
  destruct lst. (* case analysis *)
  - trivial.
  - simpl.  (* can't proceed *)
Abort.

(* Case analysis doesn't work. We need to apply _induction_ *)

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

(** Induction on lists

Here's the structure of a proof by induction on a list:

<<
Theorem.  For all lists lst, P(lst).

Proof.  By induction on lst.

For the base case,

Case:  lst = []
Show:  P([])

For the inductive case,

Case:  lst = h::t
IH:    P(t)
Show:  P(h::t)

QED.
>>

Here's how that proof could be written:

<<
Theorem:  for all lists lst, lst ++ [] = lst.

Proof:  by induction on lst.
P(lst) = lst ++ [] = lst.

Case:  lst = []
Show:
  P([])
= [] ++ [] = []
= [] = []

Case:  lst = h::t
IH: P(t) = (t ++ [] = t)
Show
  P(h::t)
= (h::t) ++ [] = h::t     // by definition of P
= h::(t ++ []) = h::t     // by definition of ++
= h::t = h::t             // by IH

QED
>>

In Coq, we could prove that theorem as follows:
*)

Theorem app_nil : forall (A:Type) (lst : list A),
  lst ++ nil = lst.
Proof.
 intros A lst.
 induction lst. (* new tactic *)
- simpl. trivial.
- simpl.
  rewrite -> IHlst. (* new tactic *)
  trivial.
Qed.

Print app_nil.

Check list_ind.

Theorem app_assoc : forall (A:Type) (l1 l2 l3 : list A),
  l1 ++ (l2 ++ l3) = (l1 ++ l2) ++ l3.
Proof.
  intros A l1 l2 l3.
  induction l1.
  - simpl. trivial.
  - simpl. rewrite <- IHl1. trivial.
Qed.

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

** Induction on natural numbers

Prove [0 + 1 + ... + n = n * (n+1) / 2].

The structure of a proof by induction on the naturals is as follows:

<<
Theorem.  For all natural numbers n, P(n).

Proof.  By induction on n.

Case:  n = 0
Show:  P(0)

Case:  n = k+1
IH:    P(k)
Show:  P(k+1)

QED.
>>

In Coq, natural numbers are encoded using Peano numerals, credited to Giuseppe Peano (1858-1932).

<<
type nat = O | S of nat
>>

- 0 is [O]
- 1 is [S O]
- 2 is [S (S O)]
- 3 is [S (S (S O))]
- etc.

The Coq definition of [nat] is much the same:
*)

Print nat.

(** We can even write computations using those constructors: *)

Compute S (S O).

(**
Coq responds, though, by reintroducing the syntactic sugar:
<<
= 2 : nat
>>

The Coq standard library defines many functions over [nat] using those
constructors and pattern matching, including addition, subtraction,
and multiplication.  For example, addition is defined like this:
*)

Fixpoint my_add (a b : nat) : nat :=
  match a with
  | 0 => b
  | S c => S (my_add c b)
  end.

(**

Let's get back to our goal. To prove [1+2+...+n = n * (n+1) / 2].

In Coq, it will turn out to be surprisingly tricky...

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

** Recursive functions, revisited

Here's a first attempt at defining [sum_to] *)

Fail Fixpoint sum_to (n:nat) : nat :=
  if n = 0 then 0 else n + sum_to (n-1).
(* [Fail] keyword -- expect definition to fail *)

(**
[=] returns [Prop]. We need something that returns [bool]. Such an operator is defined in the [Arith] library for us:
*)

Require Import Arith.

Locate "=?".
Check Nat.eqb.

Fail Fixpoint sum_to (n:nat) : nat :=
  if n =? 0 then 0 else n + sum_to (n-1).

(** A digression. Let's look at a different recursive function---one that implements an infinite loop: *)

Fail Fixpoint inf (x:nat) : nat := inf x.

(**
  + Coq does not permit any infinite loops

Consider [inf] in OCaml:

<<
# let rec inf x = inf x
val inf : 'a -> 'b = <fun>
>>

  + Type ['a -> 'b] would be [A -> B] in Coq.
  + If [A] is [True] and [B] is [False], then [inf] would be evidence for [True -> False].
  + We can derive contradiction by [inf I]!!!

Can't we just rule out infinite programs?

  + But _halting problem_ is undecidable:  we can't write a program that precisely determines whether another program will terminate.
  + Coq goes for imprecise solution -- recursive calls must be on syntactically smaller term.
    - [n] syntactically smaller than [n+1]
    - [n-1] syntactically larger than [n].
*)

Fail Fixpoint sum_to (n:nat) : nat :=
  if n =? 0 then 0 else n + sum_to (n-1).

Fixpoint sum_to (n:nat) : nat :=
  match n with
  | 0 => 0
  | S k => n + sum_to k
  end.

Print nat.

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

(** Inductive proof of the summation formula

Here's how we would write the proof mathematically:

<<
Theorem:  for all natural numbers n, sum_to n = n * (n+1) / 2.

Proof:  by induction on n.
P(n) = sum_to n = n * (n+1) / 2

Case:  n=0
Show:
  P(0)
= sum_to 0 = 0 * (0+1) / 2
= 0 = 0 * (0+1) / 2         // simplifying sum_to 0
= 0 = 0                     // 0 * x = 0

Case:  n=k+1
IH:  P(k) = sum_to k = k * (k+1) / 2
Show:
  P(k+1)
= sum_to (k+1) = (k+1) * (k+1+1) / 2
= k + 1 + sum_to k = (k+1) * (k+1+1) / 2          // simplifying sum_to (k+1)
= k + 1 + k * (k+1) / 2 = (k+1) * (k+1+1) / 2     // using IH
= 2 + 3k + k*k = 2 + 3k + k*k                     // simplifying terms on each side

QED
>>

Now let's do the proof in Coq. *)

Theorem sum_sq : forall n : nat,
  sum_to n = n * (n+1) / 2.
Proof.
  intros n.
  induction n.
  - simpl. trivial.
  - simpl. rewrite -> IHn.
Abort.

(** [Nat.divmod] is integer division.

To avoid having to reason about division, multiply both sides by 2 *)

Theorem sum_sq_no_div : forall n : nat,
  2 * sum_to n = n * (n+1).
Proof.
  intros n.
  induction n.
  - trivial.
  - simpl.
Abort.

(** [simpl] is too agressive! Let's define a helper _lemma_. *)

(* + Natural numbers with [+] and [*] form a _ring_
     - https://en.wikipedia.org/wiki/Ring_(mathematics)
   + Coq has good support for proofs on rings
*)

Lemma sum_helper : forall n : nat,
  2 * sum_to (S n) = 2 * (S n) + 2 * sum_to n.
Proof.
  intros n. simpl.
  ring. (* new tactic *)
Qed.

(** Now that we have our helper lemma, we can use it to prove the theorem: *)

Theorem sum_sq_no_div : forall n : nat,
  2 * sum_to n = n * (n+1).
Proof.
  intros n.
  induction n.
  - trivial.
  - rewrite sum_helper.
    rewrite IHn.
    ring.
Qed.

(**

Finally, we can use [sum_sq_no_div] to prove the original theorem involving
division.  To do that, we need to first prove another lemma that shows we can
transform a multiplication into a division: *)

Lemma div_helper : forall a b c : nat,
  c <> 0 -> c * a = b -> a = b / c.
Proof.
  intros a b c neq eq.
  rewrite <- eq.
  rewrite Nat.mul_comm.
  rewrite Nat.div_mul.
  trivial.
  assumption.
Qed.

(**
That lemma involves two library theorems, [mult_comm] and [Nat.div_mul]. How
did we know to use these?  Coq can help us search for useful theorems. Right
after we [rewrite <- eq] in the above proof, our subgoal is [a = c * a / c]. It
looks like we ought to be able to cancel the [c] term on the right-hand side.
So we can search for a theorem that would help us do that.  The [Search] command
takes wildcards and reports all theorems that match the pattern we supply, for
example:
*)

Search (_ * _ / _).

(** This reveals a useful theorem:
<<
Nat.div_mul: forall a b : nat, b <> 0 -> a * b / b = a
>>
That would let us cancel a term from the numerator and denominator, but it
requires the left-hand side of the equality to be of the form [a * b / b],
whereas we have [b * a / b].  The problem is that the two sides of the
multiplication are reversed.  No worries; multiplication is commutative, and
there is a library theorem that proves it. Again, we could find that theorem: *)

Search (_ * _ = _ * _).

(** One of the results is:
<<
Nat.mul_comm: forall n m : nat, n * m = m * n
>>

Putting those two library theorems to use, we're able to prove the lemma as
above.

Finally, we can use that lemma to prove our classic theorem about summation. *)

Theorem sum_sq : forall n : nat,
  sum_to n = n * (n+1) / 2.

Proof.
  intros n.
  apply div_helper.
  - discriminate.
  - rewrite sum_sq_no_div. trivial.
Qed.

(** When we use [apply div_helper] in that proof, Coq generates two new
subgoals---one for each of the propositions [c <> 0] and [c * a = b] in the type
of [div_helper].

_Summary_:  wow, that was a lot of work to prove that seemingly simple classic
theorem!  We had to figure out how to code [sum_to], and we had to deal with a
lot of complications involving algebra.  This situation is not uncommon:  the
theorems that we think of as easy with pencil-and-paper (like arithmetic) turn
out to be hard to convince Coq of, whereas the theorems that we think of as
challenging with pencil-and-paper (like induction) turn out to be easy.
*)

(**

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

** Extraction

Coq makes it possible to _extract_ OCaml code (or Haskell or Scheme) from
Coq code.  That makes it possible for us to

- write Coq code,
- prove the Coq code is correct, and
- extract OCaml code that can be compiled and run more efficiently
  than the original Coq code.

Let's first prove that a tail recursive factorial is equivalent to the non-tail-recursive one, and then extract the code for the tail recursive factorial.

*)

Fixpoint fact (n:nat) : nat :=
  match n with
  | 0 => 1
  | S k => n * fact k
  end.

Fixpoint fact_tail_rec' (n : nat) (acc: nat) : nat :=
  match n with
  | 0 => acc
  | S k => fact_tail_rec' k (acc * n)
  end.

Definition fact_tail_rec (n : nat) := fact_tail_rec' n 1.

Theorem fact_tail_rec_ok' : forall n, fact n = fact_tail_rec n.
Proof.
  unfold fact_tail_rec.
  induction n.
  - simpl. trivial.
  - simpl. rewrite IHn.
Abort.

(**

We need to prove an intermediate lemma about [fact_tail_rec'] for the proof of our main theorem to go through.

*)

Lemma fact_tail_rec_lem : forall n acc,
  fact_tail_rec' n acc = acc * fact_tail_rec' n 1.
Proof.
  intros n.
  induction n.
  - intro acc. simpl. ring.
  - intro acc. simpl.
    rewrite (IHn (acc * S n)). (* to get the correct term to reduce *)
    rewrite (IHn (S (n + 0))).
    ring.
Qed.

(**

Now we are ready to prove our main theorem. The proof involves induction on the input and an application of the lemma [fact_tail_rec_lem] that we had proved.

*)

Theorem fact_tail_rec_ok : forall n, fact n = fact_tail_rec n.
Proof.
  unfold fact_tail_rec.
  induction n.
  - simpl. trivial.
  - simpl. rewrite fact_tail_rec_lem. rewrite <- IHn. ring.
Qed.

(**

Let's extract [fact_tail_rec] as an example.

*)

Require Import Extraction.
Extraction Language OCaml.
Extraction "/tmp/fact.ml" fact_tail_rec.

(**

That produces the following file:

<<

type nat =
| O
| S of nat

(** val add : nat -> nat -> nat **)

let rec add n m =
  match n with
  | O -> m
  | S p -> S (add p m)

(** val mul : nat -> nat -> nat **)

let rec mul n m =
  match n with
  | O -> O
  | S p -> add m (mul p m)

(** val fact_tail_rec' : nat -> nat -> nat **)

let rec fact_tail_rec' n acc =
  match n with
  | O -> acc
  | S k -> fact_tail_rec' k (mul acc n)

(** val fact_tail_rec : nat -> nat **)

let fact_tail_rec n =
  fact_tail_rec' n (S O)

>>

As you can see, Coq has preserved the [nat] type in this extracted
code.  Unforunately, computation on natural numbers is not efficient.
(Addition requires linear time; multiplication, quadratic!)

We can direct Coq to extract its own [nat] type to OCaml's [int]
type as follows:

*)

Extract Inductive nat =>
  int [ "0" "succ" ] "(fun fO fS n -> if n=0 then fO () else fS (n-1))".
Extract Inlined Constant Init.Nat.mul => "( * )".

(**
The first command says to

- use [int] instead of [nat] in the extract code,
- use [0] instead of [O] and [succ] instead of [S]
  (the [succ] function is in [Pervasives] and is [fun x -> x + 1]), and
- use the provided function to emulate pattern matching over the type.

The second command says to use OCaml's integer [( * )] operator instead of
Coq's natural-number multiplication operator.

After issuing those commands, the extraction looks cleaner:

*)

Extraction "/tmp/fact.ml" fact_tail_rec.

(**
<<

(** val fact_tail_rec' : int -> int -> int **)

let rec fact_tail_rec' n acc =
  (fun fO fS n -> if n=0 then fO () else fS (n-1))
    (fun _ -> acc)
    (fun k -> fact_tail_rec' k (( * ) acc n))
    n

(** val fact_tail_rec : int -> int **)

let fact_tail_rec n =
  fact_tail_rec' n (succ 0)

>>

There is, however, a tradeoff.  The original version we extracted worked
(albeit inefficiently) for arbitrarily large numbers without any error.
But the second version is subject to integer overflow errors.  So the
proofs of correctness that we did for [fact_tail_rec] are no longer completely
applicable:  they hold only up to the limits of the types we subsituted
during extraction.

Do we truly care about the limits of machine arithmetic?  Maybe, maybe not.
For sake of this little example, we might not.  If we were verifying
software to control the flight dynamics of a space shuttle, maybe we
would.  The Coq standard library does contain a module 31-bit
integers and operators on them, which we could use if we wanted to
precisely model what would happen on a particular architecture.

*)


(* Taken from: http://www.enseignement.polytechnique.fr/informatique/INF551/TD/TD5/ *)

Require Import List ssreflect ssrbool.
From mathcomp Require Import eqtype ssrnat.

(* Let's see how one would define insertion sort in OCaml:

   let rec insert n l =
     match l with
       | [] -> [n]
       | x::xs -> if n <= x then n::x::xs else x::(insert n xs)

   let rec sort l =
     match l with
       | [] -> []
       | x::xs -> insert x (sort xs)

   As you saw during the lesson, the [insert] function is just some
   particular proof of [nat -> list nat -> list nat]: it is the proof
   that builds a new list by inserting its first arguments into its
   second one. As any proof, it thus can be defined in Coq using tactics.
 *)

Definition insert (n:nat) (l:list nat) : list nat.
Proof.
  (* The OCaml program is a recursive definition over l. I just do
     exactly the same with the elim tactic. The induction hypothesis ih
     is a proof of insert n xs : in fact it is the recursive call. *)
  elim:l => [|x xs ih].
  (* We start with the base case: we return the singleton list
     containing only n. *)
   apply:(n::nil).
  (* We are now in the recursive case. We need to distinguish two cases
     whether n <= x or not. *)
  case h:(n <= x).
  (* We are in the branch where n <= x. In this case, we can immediately
     return the list n::x::xs *)
    apply:(n::x::xs).
  (* We now are in the branch where n > x. In this case, we want to
     return x::(insert n xs). As we said, the recursive call is in fact
     ih. *)
  apply:(x::ih).
  (* Our function is now defined using tactics. [Defined] checks that it
     actually have the right type and defines it. *)
 Defined.

(* We can check on some examples that it is indeed the insert function
   we add in mind. Coq can actually compute with it! *)

Compute (insert 5 (1::2::3::4::6::7::8::9::nil)).
Compute (insert 5 (1::2::3::4::nil)).

(* Now do the same for the sort function, and test it on some examples.
   Hint: it takes only three tactics to define it! *)

Definition sort (l:list nat) : list nat.
Proof.
  (* Break up the recursive definition and get the induction hypothesis. *)
  elim:l => [|x xs ih].
  (* first the base case which is the empty list *)
  apply:(nil).
  (* the step case which is the recursive call which inserts the current element
     and sorts the rest of the list. *)
  apply:(insert x ih).
Defined.

Compute (sort (7::9::5::3::0::4::2::1::8::6::nil)).
(* Add your own examples... *)
Compute (sort (1::0::2::3::nil)).
Compute (sort (0::1::2::nil)).

(* Ok, so far we have understood that we can define function using
   tactics. But our sorting function is no more that the OCaml version:
   we did not prove it was actually returning a list that is sorted!
   With tactics, we will be able to build the sorting function AND proof
   its correctness at the same time... *)

(* First, we need to define for a list of integers what it means to be
   sorted: each element is smaller than all the following elements *)

Fixpoint smaller n l : Prop :=
  match l with
    | nil => true
    | x::xs => n <= x /\ smaller n xs
  end.

Fixpoint sorted l : Prop :=
  match l with
    | nil => true
    | x::xs => smaller x xs /\ sorted xs
  end.

(* We give a very simple fact about smaller: if a is smaller than all
   the elements of a list l, and n <= a, then n is also smaller than all
   the elements of l. *)

Lemma smaller_trans n a l : smaller a l -> n <= a -> smaller n l.
Proof.
  elim:l => /=.
    done.
  move => b l ih.
  move => [h1 h2] h3.
  split.
    move/(_ a n b):leq_trans => h4.
    by apply:h4.
  by apply:ih.
Defined.

(* For a matter of time, we also give you some arithmetic lemmas that
   you will need:

   o leq_false_lt m n : (m <= n) = false -> (n < m)
   o leq_false_leq n x : (n <= x) = false -> x <= n
   o eq_refl (n:nat) : n == n
   o gtn_eqF m n : m < n -> n == m = false
   o leq_false_neq n a : (n <= a) = false -> n == a = false

   Do not look at the proofs, just look at the statements above. *)

Lemma leq_trans n m p : m <= n -> n <= p -> m <= p.
Proof.
  elim: n m p => [|i IHn] [|m] [|p]; try reflexivity.
        move => h _. apply:h.
      compute. discriminate 1.
    move => _. compute => h. apply:h.
  by move/(_ m p):IHn.
Defined.

Lemma ltnW m n : m < n -> m <= n.
Proof. by apply:leq_trans. Defined.

Lemma leq_false_lt m n : (m <= n) = false -> (n < m).
Proof.
  elim: m n => [|m IHm] [|n].
        compute. discriminate 1.
      compute. discriminate 1.
    reflexivity.
  by move/(_ n):IHm.
Defined.

Lemma leq_false_leq n x : (n <= x) = false -> x <= n.
Proof.
  move => h.
  apply:ltnW.
  by apply:leq_false_lt.
Defined.

Lemma eq_refl (n:nat) : n == n.
Proof.
  elim:n => [|n ih].
    reflexivity.
  exact:ih.
Defined.

Lemma leqNgt m n : (m <= n) = ~~ (n < m).
Proof. by elim: m n => [|m IHm] [|n] //; exact: IHm n. Defined.

Lemma eqn_leq m n : (m == n) = (m <= n <= m).
Proof. elim: m n => [|m IHm] [|n] //; exact: IHm n. Defined.

Lemma gtn_eqF m n : m < n -> n == m = false.
Proof. by rewrite eqn_leq (leqNgt n) => ->. Defined.

Lemma leq_false_neq n a : (n <= a) = false -> n == a = false.
Proof.
  move => h.
  apply:gtn_eqF.
  by apply: leq_false_lt.
Defined.

(* We are now ready to build the insert function and prove its
   correctness at the same time. To do so, the Coq writing {l | P l}
   that designates a list l that satisfies the predicate P: P is the
   specification of the function.

   The specification of the insert function is the following:
   o if a is smaller that all the elements of l and a <= n then a is
     smaller than all the elements of (insert n l)
   o if l is sorted then (insert n l) is sorted *)

Definition insert_spec n l :
  {l' |
    (forall a, smaller a l -> a <= n -> smaller a l') /\
    (sorted l -> sorted l')}.
Proof.
  (* The proof is a refinement of the proof of [insert], in which we
     also build the proof of the specification of the function. So like
     for defining [insert], we do an induction. *)
  elim:l => [|x xs ih].
  (* We present the base case. The answer is the singleton list
     containing only n, together with a proof that this list satisfies
     the specification. We first give the list, using the exists tactic.
     *)
    exists (n::nil).
    (* Let's now prove the specification. It is a conjunction. *)
    split.
    (* On the first branch, we introduce a. *)
      move => a.
      (* We can simplify this goal: we know what [smaller a nil] and
         [smaller a (n :: nil)] mean. *)
      simpl.
      (* In fact, this goal is trivially proved with done. *)
      done.
      (* Let's simplify the second branch: we know what [sorted nil] and
         [sorted (n :: nil)] mean. *)
    simpl.
    (* In fact, this goal is trivially proved with done. *)
    done.
    (* Now do the recursive case. Do not forget to make a case analysis
       whether n <= x or not. You can destruct a proof of {l | P l}
       using the [case] tactic as usual. *)
  case:ih => [l4 [ih1 ih2]].
  case h:(n <= x).
    (* n is smaller then x *)
    exists (n::x::xs).
    split => //.
    move => [h1 h2].
    split => //.
    split => //.
    apply:(smaller_trans _ _ _ h1).
    done.
    (* n is greater then x *)
    exists (x::l4) => /=.
    split.
    move => a.
    move => [h1 h2].
    move => h3.
    split => //.
     by apply ih1.
    move => [h1 h2].
    split.
    apply:ih1 => //.
     by apply leq_false_leq.
      by apply ih2.
Defined.

(* Let do the same for the sort function. *)

Definition sort_spec (l:list nat) : {l' | sorted l'}.
Proof.
  elim:l => [| x xs [l4 ih]].
  (* base case *)
  exists (nil).
  done.
  (* step case *)
  case (insert_spec x l4) => [l5 [h1 h2]].
  exists (l5).
   by apply h2.
Defined.

(* We now have defined functions that are correct (with respect to our
   specification) by construction. Finally, Coq offers an extraction
   mechanism, that automatically export them to OCaml, so we are sure
   that the OCaml program is correct by construction. *)

Require Extraction.
Extraction Language Ocaml.
Set Extraction AccessOpaque.

Extraction "insert_sort.ml" sort_spec.

(* Have a look at the file "insert_sort.mli". You observe that the
   function [sort_spec] has type [nat list -> nat list]: the extraction
   mechanism "forgets" the proof of the correctness of this function,
   since it has no signification in OCaml. You can test this extracted
   function using the file "test_sort.ml". *)

(* TO GO FURTHER *)

(* I am sure you all have noticed that our specification is incomplete:
   the sort function must not only return a sorted list, but this list
   must be a permutation of the initial list! We now do the same job
   with a complete specification. *)

(* We first define our notion of permutation: (x::xs) and l2 are a
   permutation if and only if xs and (remove x l2) are. *)

Fixpoint remove a (l:list nat) :=
  match l with
    | nil => None
    | x::xs =>
      if a == x then
        Some xs
      else
        match remove a xs with
          | Some xs' => Some (x::xs')
          | None => None
        end
  end.

Fixpoint permutation l1 l2 : Prop :=
  match l1, l2 with
    | nil, nil => true
    | nil, _ => False
    | x::xs, _ =>
      match remove x l2 with
        | Some l2' => permutation xs l2'
        | None => False
      end
  end.

(* First prove that this relation is reflexive. *)

Lemma permutation_refl l: permutation l l.
Proof.
  (* TODO *)
Defined.

(* Now define insertion and sort with the complete specification. *)

Definition insert_complete n l :
  {l' |
    (forall a, smaller a l -> a <= n -> smaller a l') /\
    (remove n l' = Some l) /\
    (sorted l -> sorted l' /\ permutation (n::l) l')}.
Proof.
  (* TODO *)
Defined.

Definition sort_complete (l:list nat) : {l' | sorted l' /\ permutation l l'}.
Proof.
  (* TODO *)
Defined.

Extraction Language Ocaml.
Set Extraction AccessOpaque.

Extraction "insert_sort.ml" sort_complete.


Module Playgroud1.

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

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

End Playgroud1.

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

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

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

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

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

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

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

End Playground2.

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

Fixpoint factorial (n : nat) : nat :=
  match n with
  | O => 1
  | 1 => 1
  | (S n') => (mult n (factorial n'))
  end.
Example test_factorial1: (factorial 3) = 6.
Proof. reflexivity. Qed.
Example test_factorial2: (factorial 5) = (mult 10 12).
Proof. reflexivity. Qed.

Notation "x + y" := (plus x y)
                      (at level 50, left associativity)
                      : nat_scope.
Notation "x - y" := (minus x y)
                      (at level 50, left associativity)
                      : nat_scope.
Notation "x * y" := (mult x y)
                      (at level 40, left associativity)
                      : nat_scope.
Fixpoint beq_nat (n m : nat) : bool :=
  match n with
  | O => match m with
         | O => true
         | _ => false
    end
  | S n' => match m with
            | O => false
            | S m' => (beq_nat n' m')
    end
  end.

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

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

Definition blt_nat (n m : nat) : bool :=
  (andb (ble_nat n m) (negb (beq_nat n m))).

Example test_blt_nat1: (blt_nat 2 2) = false.
Proof. reflexivity. Qed.
Example test_blt_nat2: (blt_nat 2 4) = true.
Proof. reflexivity. Qed.
Example test_blt_nat3: (blt_nat 4 2) = false.
Proof. reflexivity. Qed.

Definition bgt_nat (n m : nat) : bool := negb (ble_nat n m).
Definition bge_nat (n m : nat) : bool := negb (blt_nat n m).

(* proof by simplification *)

Theorem plus_0_n : forall n: nat, 0 + n = n.
Proof.
  intro n.
  reflexivity.
Qed.

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

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

(* proof by rewriting *)

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

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

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

Theorem mult_S_1 : forall n m : nat,
  m = S n -> m * (1 + n) = m * m.
Proof.
  intros n m.
  intro H.
  rewrite plus_1_l.
  rewrite H.
  reflexivity.
Qed.

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

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

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall b : bool, f (f b) = b.
Proof.
  intros.
  rewrite H.
  rewrite H.
  reflexivity.
Qed.

Theorem negation_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = negb x) ->
  forall b : bool, f (f b) = b.
Proof.
  intros.
  rewrite H.
  rewrite H.
  destruct b; (compute; reflexivity).
Qed.

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) -> b = c.
Proof.
  intros b c.
  destruct b, c; simpl.
  reflexivity.
  intro. rewrite H. reflexivity.
  intro. rewrite H. reflexivity.
  reflexivity.
Qed.

Inductive bin : Type :=
  | O : bin
  | T2 : bin -> bin
  | T1 : bin -> bin.

Fixpoint inc(n : bin) :=
  match n with
  | O => T1 O
  | T1 a => T2 (inc a)
  | T2 a => T1 a
  end.

Example inc_O_is_T1O : inc O = T1 O.
Proof. reflexivity. Qed.
Example inc_1_is_T2T1O : inc (T1 O) = T2 (T1 O).
Proof. reflexivity. Qed.
Example inc_2_is_T1T10 : inc (T2 (T1 O)) = T1 (T1 O).
Proof. reflexivity. Qed.
Example inc_3_is_T2T20 :
  inc (T1 (T1 O)) = T2 (T2 (T1 O)).
Proof. reflexivity. Qed.

Fixpoint bin2nat(n : bin) : nat :=
  match n with
  | O => 0
  | T1 a => (bin2nat a) * 2 + 1
  | T2 a => (bin2nat a) * 2
  end.

(* TODO *)

(*
Fixpoint nat2bin(n : nat) : bin :=
  match n with
  | 0 => O
  | evenb n     => T2 (nat2bin n)
  | oddbb 1 => T1 (nat2bin n)
  end.
  *)

(*
   exercise: write a fix-point definition that
   does terminate on all input but coq does not
   accept because of this restriction.
*)

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

(* this is cool *)


Require Import Arith.
Theorem restricted_excluded_middle
  : forall P b, (P <-> b = true) -> P \/ not P.
Proof.
  intros P b H.
  destruct b.
  - left. apply H. reflexivity.
  - right. intros F. apply H in F. inversion F.
Qed.

Theorem restricted_excluded_middle_eq
  : forall (n m: nat), n = m \/ n <> m.
Proof.
  intros n m.
  apply (restricted_excluded_middle (n = m) (Nat.eqb n m)).
  symmetry.
  apply Nat.eqb_eq.
Qed.