(** * Extract: Running Coq Programs in OCaml *)

(** Coq's [Extraction] feature enables you to write a functional
    program inside Coq, use Coq's logic to prove some correctness
    properties about it, and translate it into an OCaml program that
    you can compile with your optimizing OCaml compiler.  Haskell is
    also supported. *)

(** The [Extraction] chapter of _Logical Foundations_ has
    a simple example of Coq's program extraction features, but it's
    not required reading. This chapter starts from scratch and goes
    deeper. *)

From VFA Require Import Perm.
Require Extraction.

(* ################################################################# *)
(** * Extraction *)

(** As an example, let's extract insertion sort, which we implemented
    in [Sort]. *)

Fixpoint ins (i : nat) (l : list nat) :=
  match l with
  | [] => [i]
  | h :: t => if i <=? h then i :: h :: t else h :: ins i t
  end.

Fixpoint sort (l : list nat) : list nat :=
  match l with
  | [] => []
  | h :: t => ins h (sort t)
  end.

(** The [Extraction] command prints out a function as OCaml code. *)

Extraction sort.

(** You can see the translation of [sort] from Coq to OCaml in
    your IDE.  Examine it there, and notice the similarities and
    differences.  To get the whole program, we need [Recursive
    Extraction]: *)

Recursive Extraction sort.

(** The first thing you see there is a redefinition of the [bool] type.
    But OCaml already has a [bool] type whose inductive structure is
    isomorphic. We want our extracted functions to be compatible
    with, i.e. callable by, ordinary OCaml code. So we want to use
    OCaml's standard definition of [bool] in place of Coq's inductive
    definition, [bool]. You'll notice the same issue with lists. The
    following directive causes Coq to use OCaml's definitions of [bool]
    and [list] in the extracted code: *)

Extract Inductive bool => "bool" [ "true" "false" ].
Extract Inductive list => "list" [ "[]" "(::)" ].
Recursive Extraction sort.

(** But the program still uses a unary representation of natural
    numbers: the number 7 is really [(S (S (S (S (S (S (S O)))))))],
    which in OCaml will be a data structure that's seven pointers
    deep. The [leb] function takes linear time, proportional to the
    difference in value between [n] and [m]. *)

(** We could instead use Coq's [Z], which is a binary representation
    of integers. But that is logarithmic-time, not constant. *)

Require Import ZArith.
Open Scope Z_scope.

Fixpoint insertZ (i : Z) (l : list Z) :=
  match l with
  | [] => [i]
  | h :: t => if i <=? h then i :: h :: t else h :: insertZ i t
  end.

Fixpoint sortZ (l : list Z) : list Z :=
  match l with
  | [] => []
  | h :: t => insertZ h (sortZ t)
  end.

Recursive Extraction sortZ.

(** Of course, for that extraction to be meaningful, we would need
    to prove that [sortZ] is a sorting algorithm. *)

(** Other alternatives include:

    - Extract [nat] directly to OCaml [int].  But [int] is finite (2^63
      in modern implementations), so there are theorems we could prove
      in Coq that wouldn't hold in OCaml.

    - Use Coq's [Int63], which faithfully models 63-bit cyclic
      arithmetic, and extract directly to OCaml [int]. But that's
      painful.

    - Define and axiomatize our own lightweight abstract type of
      naturals, but extract it to OCaml [int].  But, this is
      dangerous! If our axioms are inconsistent, we can prove anything
      at all. If they are not faithful to OCaml, our proofs will be
      meaningless. *)

(* ################################################################# *)
(** * Lightweight Extraction to [int] *)

(** We begin by positing a Coq type [int] that will be extracted to
    OCaml's [int]: *)

Parameter int : Type.
Extract Inlined Constant int => "int".

(** We'll abstract OCaml [int] to Coq [Z].  Every [int] does have a
    representation as a [Z], though the other direction cannot
    hold. *)

Parameter Abs : int -> Z.
Axiom Abs_inj: forall (n m : int), Abs n = Abs m -> n = m.

(** Nothing else is known so far about [int]. Let's add a less-than
    operators, which are extracted to OCaml's: *)

Parameter ltb: int -> int -> bool.
Extract Inlined Constant ltb => "(<)".
Axiom ltb_lt : forall (n m : int), ltb n m = true <-> Abs n < Abs m.

Parameter leb: int -> int -> bool.
Extract Inlined Constant leb => "(<=)".
Axiom leb_le : forall (n m : int), leb n m = true <-> Abs n <= Abs m.

(** Those axioms are sound: OCaml's [<] and [<=] are consistent with
    Coq's on any [int]. Note that we do not give extraction directives
    for [Abs], [ltb_lt], or [leb_le].  They will not appear in
    programs, only in proofs --which are not meant to be extracted. *)

(** You could imagine doing the same thing we just did with [(+)], but
    that would be wrong:

      Parameter ocaml_plus : int -> int -> int.
      Extract Inlined Constant ocaml_plus => "(+)".
      Axiom ocaml_plus_plus: forall a b c: int,
        ocaml_plus a b = c <-> Abs a + Abs b = Abs c.

    The first two lines are OK: there really is a [+] function in
    OCaml, and its type really is [int -> int -> int].

    But [ocaml_plus_plus] is unsound. From it, you could prove,

      Abs max_int + Abs max_int = Abs (ocaml_plus max_int max_int)

    which is not true in OCaml because of overflow.

*)

(** In [Perm] we proved several theorems showing that Boolean
    operators were reflected in propositions.  Below, we do that
    for [int] and [Z] comparisons. *)

Lemma int_ltb_reflect : forall x y, reflect (Abs x < Abs y) (ltb x y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply ltb_lt.
Qed.

Lemma int_leb_reflect : forall x y, reflect (Abs x <= Abs y) (leb x y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply leb_le.
Qed.

Lemma Z_eqb_reflect : forall x y, reflect (x = y) (Z.eqb x y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply Z.eqb_eq.
Qed.

Lemma Z_ltb_reflect : forall x y, reflect (x < y) (Z.ltb x y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply Z.ltb_lt.
Qed.

Lemma Z_leb_reflect : forall x y, reflect (x <= y) (Z.leb x y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. apply Z.leb_le.
Qed.

Lemma Z_gtb_reflect : forall x y, reflect (x > y) (Z.gtb x y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. rewrite Z.gtb_ltb. rewrite Z.gt_lt_iff. apply Z.ltb_lt.
Qed.

Lemma Z_geb_reflect : forall x y, reflect (x >= y) (Z.geb x y).
Proof.
  intros x y.
  apply iff_reflect. symmetry. rewrite Z.geb_leb. rewrite Z.ge_le_iff. apply Z.leb_le.
Qed.

(** Now we upgrade [bdall] to work with [Z] and [int].  *)

Hint Resolve
     int_ltb_reflect int_leb_reflect
     Z_eqb_reflect Z_ltb_reflect Z_leb_reflect Z_gtb_reflect Z_geb_reflect
  : bdestruct.

Ltac bdestruct_guard:=
  match goal with
  | |- context [ if Nat.eqb ?X ?Y then _ else _] => bdestruct (Nat.eqb X Y)
  | |- context [ if Nat.ltb ?X ?Y then _ else _] => bdestruct (Nat.ltb X Y)
  | |- context [ if Nat.leb ?X ?Y then _ else _] => bdestruct (Nat.leb X Y)
  | |- context [ if Z.eqb ?X ?Y then _ else _] => bdestruct (Z.eqb X Y)
  | |- context [ if Z.ltb ?X ?Y then _ else _] => bdestruct (Z.ltb X Y)
  | |- context [ if Z.leb ?X ?Y then _ else _] => bdestruct (Z.leb X Y)
  | |- context [ if Z.gtb ?X ?Y then _ else _] => bdestruct (Z.gtb X Y)
  | |- context [ if Z.geb ?X ?Y then _ else _] => bdestruct (Z.geb X Y)
  | |- context [ if ltb ?X ?Y then _ else _] => bdestruct (ltb X Y)
  | |- context [ if leb ?X ?Y then _ else _] => bdestruct (leb X Y)
  end.

Ltac bdall :=
  repeat (simpl; bdestruct_guard; try omega; auto).

(* ################################################################# *)
(** * Insertion Sort, Extracted *)

(** We're ready to state insertion sort with [int], and to extract it: *)

Fixpoint ins_int (i : int) (l : list int) :=
  match l with
  | [] => [i]
  | h :: t => if leb i h then i :: h :: t else h :: ins_int i t
  end.

Fixpoint sort_int (l : list int) : list int :=
  match l with
  | [] => []
  | h :: t => ins_int h (sort_int t)
  end.

Recursive Extraction sort_int.

(** Again, for that extraction to be meaningful, we need to prove that
    [sort_int] is a sorting algorithm.  We can do that with the same
    techniques we used in [Sort].  In particular, [omega] works
    with [Z], so we can enjoy automation without having to do any
    unnecessary work axiomatizing and proving lemmas about [int]. *)

Inductive sorted : list int -> Prop :=
| sorted_nil:
    sorted []
| sorted_1: forall x,
    sorted [x]
| sorted_cons: forall x y l,
    Abs x <= Abs y -> sorted (y :: l) -> sorted (x :: y :: l).

Hint Constructors sorted.

Lemma insert_sorted:
  forall a l, sorted l -> sorted (ins_int a l).
Proof.
  intros a l S. induction S; simpl.
  - constructor.
  - bdall; auto.
    constructor; auto. omega.
  - bdall; auto.
    bdall.
    + constructor; auto. omega.
    + constructor; auto.
      simpl in IHS. bdestruct (leb a y); auto.
      unfold not in H0. unfold not in H1. auto. omega.
Qed.

Theorem sort_sorted: forall l, sorted (sort_int l).
Proof.
  induction l; simpl; auto.
  apply insert_sorted. auto.
Qed.

Lemma insert_perm: forall x l,
    Permutation (x :: l) (ins_int x l).
Proof.
  induction l; simpl.
  - apply Permutation_refl.
  - destruct (leb x a).
    + apply Permutation_refl.
    + apply perm_trans with (a :: x :: l).
      * apply perm_swap.
      * apply perm_skip. assumption.
Qed.

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

(** Prove the correctness of [sort_int] by adapting your solution to
    [insertion_sort_correct] from [Sort]. *)

Theorem sort_int_correct : forall (al : list int),
    Permutation al (sort_int al) /\ sorted (sort_int al).
Proof.
  split.
  - induction al.
    apply Permutation_refl.
    simpl. apply Permutation_trans with (a :: (sort_int al)).
    apply perm_skip. assumption.
    + apply insert_perm.
  - apply sort_sorted.
Qed.

(** [] *)

(* ################################################################# *)
(** * Binary Search Trees, Extracted *)

(** We can reimplement BSTs with [int] keys. *)

Definition key := int.

Inductive tree (V : Type) : Type :=
  | E : tree V
  | T : tree V -> key -> V -> tree V -> tree V.

Arguments E {V}.
Arguments T {V}.

Definition empty_tree {V : Type} : tree V := E.

Fixpoint lookup {V : Type} (default : V) (x : key) (t : tree V) : V :=
  match t with
  | E => default
  | T l k v r => if ltb x k then lookup default x l
                else if ltb k x then lookup default x r
                     else v
  end.

Fixpoint insert {V : Type} (x : key) (v : V) (t : tree V) : tree V :=
  match t with
  | E => T E x v E
  | T l y v' r => if ltb x y then T (insert x v l) y v' r
                 else if ltb y x then T l y v' (insert x v r)
                      else T l x v r
  end.

Fixpoint elements_tr {V : Type}
         (t : tree V) (acc : list (key * V)) : list (key * V) :=
  match t with
  | E => acc
  | T l k v r => elements_tr l ((k, v) :: elements_tr r acc)
  end.

Definition elements {V : Type} (t : tree V) : list (key * V) :=
  elements_tr t [].

Theorem lookup_empty : forall (V : Type) (default : V) (k : key),
    lookup default k empty_tree = default.
Proof. auto. Qed.

(** **** Exercise: 2 stars, standard (lookup_insert_eq)  *)
Theorem lookup_insert_eq :
  forall (V : Type) (default : V) (t : tree V) (k : key) (v : V),
    lookup default k (insert k v t) = v.
Proof.
  intros. induction t.
  -  simpl. bdall.
  - simpl. bdall.
Qed.
(** [] *)

Lemma geimpeq : forall (k : int) (k' : int),
    (Abs k' >= Abs k) -> (Abs k >= Abs k') -> (Abs k' = Abs k).
Proof.
  intros. omega.
Qed.

(** **** Exercise: 3 stars, standard (lookup_insert_neq)  *)
Theorem lookup_insert_neq :
  forall (V : Type) (default : V) (t : tree V) (k k' : key) (v : V),
    k <> k' -> lookup default k' (insert k v t) = lookup default k' t.
Proof.
  intros. induction t.
  - simpl.  unfold not in H.
    bdall.  apply Znot_lt_ge in H0. apply Znot_lt_ge in H1.
    apply geimpeq in H0.  apply Abs_inj in H0. apply H in H0. inversion H0.
    apply H1.
  - simpl. bdall. apply Znot_lt_ge in H2. apply Znot_lt_ge in H3.
    apply geimpeq in H2.  apply Abs_inj in H2. apply H in H2. inversion H2.
    apply H3.
Qed.
(** [] *)

(** **** Exercise: 5 stars, standard, optional (int_elements)  *)

(** Port the definition of [BST] and re-prove the properties of
    [elements] for [int]-keyed trees. Send us your solution so
    we can include it! *)

(** [] *)

(** Now see the extraction in your IDE: *)

Extract Inductive prod => "(*)"  [ "(,)" ]. (* extract pairs natively *)
Recursive Extraction empty_tree insert lookup elements.

(* ################################################################# *)
(** * Performance Tests *)

(** Let's measure the performance of BSTs.  First, we extract to
    an OCaml file: *)

Extraction "searchtree.ml" empty_tree insert lookup elements.

(** Second, in the same directory as this file ([Extract.v])
    you will find the file [test_searchtree.ml]. You can
    run it using the OCaml toplevel with these commands:

# #use "searchtree.ml";;
# #use "test_searchtree.ml";;

On a recent machine with a 2.9 GHz Intel Core i9 that prints:

Insert and lookup 1000000 random integers in .889566 seconds.
Insert and lookup 20000 random integers in 0.009918 seconds.
Insert and lookup 20000 consecutive integers in 2.777335 seconds.

That execution uses the bytecode interpreter.  The native compiler
will have better performance:

$ ocamlopt -c searchtree.mli searchtree.ml
$ ocamlopt searchtree.cmx -open Searchtree test_searchtree.ml -o test_searchtree
$ ./test_searchtree

On the same machine that prints,

Insert and lookup 1000000 random integers in 0.488973 seconds.
Insert and lookup 20000 random integers in 0.003237 seconds.
Insert and lookup 20000 consecutive integers in 0.387535 seconds.
*)

(** Of course, the reason why the performance is so much worse with
    consecutive integers is that BSTs exhibit worst-case performance
    under that workload: linear time instead of logarithmic.  We need
    balanced search trees to achieve logarithmic.  [Redblack]
    will do that. *)

(* Mon May 11 23:21:35 EDT 2020 *)


Require Import Program.Equality Lia SimplDec.
Require Export ListExtra PreSuffix ListOrder.

Definition Tag := list nat.

Inductive Taglt : Tag -> Tag -> Prop :=
| TagltS (n m : nat) (i : Tag) : n < m -> Taglt (n :: i) (m :: i)
| TagltCons (n m : nat) (i j : Tag) : Taglt i j -> Taglt (n :: i) (m :: j).

Definition Tagle (i j : Tag) : Prop := Taglt i j \/ i = j.

Infix "⊴" := Tagle (at level 70).
Infix "◁" := Taglt (at level 70).

Lemma Tagle_refl (i : Tag)
  : i ⊴ i.
Proof.
  right;auto.
Qed.

Lemma Taglt_irrefl
  : Irreflexive Taglt.
Proof.
  unfold Irreflexive, Reflexive, complement.
  intros x Hx.
  dependent induction Hx.
  - lia.
  - auto.
Qed.

Lemma Taglt_trans
  : Transitive Taglt.
Proof.
  intros x y z Hxy Hyz.
  revert dependent z.
  dependent induction Hxy;intros.
  - dependent destruction Hyz.
    + econstructor. lia.
    + econstructor. auto.
  - dependent destruction Hyz.
    + econstructor. auto.
    + econstructor. eauto.
Qed.

Hint Resolve Taglt_irrefl Taglt_trans : tagle.

Global Instance Taglt_StrictOrder : StrictOrder Taglt.
Proof.
  split; eauto with tagle.
Qed.

Global Instance Tagle_PreOrder : PreOrder Tagle.
Proof.
  eapply StrictOrder_PreOrder;eauto.
Qed.

Global Instance Tagle_PartialOrder : PartialOrder eq Tagle.
Proof.
  eapply StrictOrder_PartialOrder;eauto.
Qed.

Lemma Taglt_non_nil1 (i : Tag)
  : [] ◁ i -> False.
Proof.
  intro H. inversion H.
Qed.

Lemma Taglt_non_nil2 (i : Tag)
  : i ◁ [] -> False.
Proof.
  intro H. inversion H.
Qed.

Hint Immediate Taglt_non_nil1 Taglt_non_nil2 : tagle.

Lemma Taglt_len (i j : Tag)
      (Htaglt : i ◁ j)
  : | i | = | j |.
Proof.
  induction Htaglt;cbn;auto.
Qed.

Lemma Taglt_rcons_le (i j : Tag) (n m : nat)
      (Htaglt : i ++ [n] ◁ j ++ [m])
  : n <= m.
Proof.
  dependent induction Htaglt.
  - rewrite cons_rcons' in x0.
    rewrite cons_rcons' in x.
    eapply app_inj_tail in x0.
    eapply app_inj_tail in x.
    do 2 destructH. subst n m.
    cbn in *.
    rinduction i0; cbn in *.
    + lia.
    + rewrite rev_rcons. cbn. reflexivity.
  - destruct i0. inversion Htaglt.
    destruct j0. inversion Htaglt.
    eapply (IHHtaglt (tl i) (tl j));eauto.
    + destruct i;cbn in *;eauto. congruence. inversion x0. eauto.
    + destruct j;cbn in *;eauto. congruence. inversion x. eauto.
Qed.

Lemma Taglt_eq_rcons_lt (i : Tag) (n m : nat)
      (Htaglt : i ++ [n] ◁ i ++ [m])
  : n < m.
Proof.
  induction i;cbn in *.
  - inversion Htaglt;subst;auto. inversion H0.
  - eapply IHi. inversion Htaglt;subst.
    + lia.
    + auto.
Qed.

Hint Immediate Taglt_irrefl : tagle.

Lemma Taglt_eq_cons_lt (i : Tag) (n m : nat)
      (Htaglt : n :: i ◁ m :: i)
  : n < m.
Proof.
  inversion Htaglt;subst;eauto.
  exfalso. eapply Taglt_irrefl; eauto.
Qed.

Lemma Taglt_eq_rcons_Taglt (i j : Tag) (n : nat)
      (Htaglt : i ++ [n] ◁ j ++ [n])
  : i ◁ j.
Proof.
  eapply Taglt_len in Htaglt as Hlen.
  do 2 rewrite length_rcons in Hlen. eapply Nat.succ_inj in Hlen.
  destruct i;[|revert dependent i; revert dependent n0];induction j;cbn in *;intros.
  - exfalso. inversion Htaglt;subst. lia. eauto with tagle.
  - lia.
  - lia.
  - dependent destruction Htaglt.
    + eapply app_inj_tail in x; destruct x;subst.
      econstructor;eauto.
    + econstructor.
      destruct i,j; cbn in *.
      1: exfalso;eapply Taglt_irrefl;eauto.
      1,2: lia.
      eapply IHj;eauto.
Qed.

Lemma Taglt_le_rcons (n m : nat) (i j : Tag)
      (Htaglt : i ◁ j)
      (Hle : n <= m)
  : i ++ [n] ◁ j ++ [m].
Proof.
  induction Htaglt;cbn.
  - eapply le_lt_or_eq in Hle. destruct Hle.
    + econstructor;eauto. induction i; cbn; econstructor; eauto.
    + subst. econstructor;eauto.
  - econstructor;eauto.
Qed.

Lemma Taglt_lt_rcons (n m : nat) (i j : Tag)
      (Hlen : |i| = |j|)
      (Hlt : n < m)
  : i ++ [n] ◁ j ++ [m].
Proof.
  destruct i; intros.
  - destruct j; cbn in *.
    + econstructor; eauto.
    + lia.
  - revert n0 i Hlen.
    induction j; cbn in *; intros.
    + lia.
    + destruct i; cbn in *.
      * destruct j; cbn in *; [|lia].
        econstructor;econstructor;eauto.
      * econstructor.
        eapply IHj.
        lia.
Qed.

Lemma Taglt_ind_r
      (P : Tag -> Tag -> Prop)
      (Hbase : forall (n m : nat) (i j : Tag), |i| = |j| -> n < m -> P (i++[n]) (j++[m]))
      (Hstep : forall (n : nat) (i j : Tag), Taglt i j -> P i j -> P (i++[n]) (j++[n]))
      (i j : Tag)
      (Htaglt : Taglt i j)
  : P i j.
Proof.
  revert dependent j.
  rinduction i. 1: exfalso; eauto with tagle.
  revert dependent l. revert dependent a.
  rinduction j. 1: exfalso; eauto with tagle.
  eapply Taglt_len in Htaglt as Hlen.
  do 2 rewrite length_rcons in Hlen. eapply Nat.succ_inj in Hlen.
  eapply Taglt_rcons_le in Htaglt as Hle.
  eapply le_lt_or_eq in Hle.
  destruct Hle.
  - eapply Hbase;eauto.
  - subst a0.
    eapply Taglt_eq_rcons_Taglt in Htaglt.
    eapply Hstep;eauto.
Qed.

Lemma taglt_tagle_trans (i j k : Tag)
  : i ◁ j -> j ⊴ k -> i ◁ k.
Proof.
  intros.
  destruct H0.
  - transitivity j;eauto.
  - subst. auto.
Qed.

Lemma tagle_taglt_trans (i j k : Tag)
  : i ⊴ j -> j ◁ k -> i ◁ k.
Proof.
  intros.
  destruct H.
  - transitivity j;eauto.
  - subst. auto.
Qed.

Lemma le_cons_tagle n1 n2 i
      (Hlt : n1 <= n2)
  : n1 :: i ⊴ n2 :: i.
Proof.
  eapply le_lt_or_eq in Hlt. destruct Hlt.
  - econstructor. econstructor. assumption.
  - subst. reflexivity.
Qed.

Lemma lt_cons_ntagle n1 n2 i
      (Hlt : n2 < n1)
  : ~ n1 :: i ⊴ n2 :: i.
Proof.
  simpl_dec.
  split.
  - intro N.
    inv N.
    + lia.
    + eapply Taglt_irrefl;eauto.
  - intro N. inv N. lia.
Qed.

Lemma taglt_trichotomy i j
      (Hlen : |i| = |j|)
  : i ◁ j \/ i = j \/ j ◁ i.
Proof.
  remember (|i|) as n.
  revert i j Heqn Hlen.
  induction n;intros.
  - destruct i,j;cbn in *;try congruence. right. left. reflexivity.
  - destruct i,j;cbn in *;try congruence.
    specialize (IHn i j).
    exploit IHn.
    destruct IHn as [IHn|[IHn|IHn]];[left| |right;right].
    + econstructor;eauto.
    + subst.
      specialize (Nat.lt_trichotomy n0 n1) as Hcase.
      destruct Hcase as [Hcase|Hcase];[left|right];[|destruct Hcase as [Hcase|Hcase];[left|right]].
      * econstructor;eauto.
      * subst. reflexivity.
      * econstructor;eauto.
    + econstructor;eauto.
Qed.

Lemma tagle_or i j
      (Hlen : |i| = |j|)
  : i ⊴ j \/ j ⊴ i.
Proof.
  eapply taglt_trichotomy in Hlen.
  destruct Hlen as [Hlen|[Hlen|Hlen]];[left;left|left;right|right;left];eauto.
Qed.

Lemma Tagle_len: forall [i j : Tag], i ⊴ j -> | i | = | j |.
Proof.
  intros. destruct H.
  - eapply Taglt_len;eauto.
  - subst. reflexivity.
Qed.


From Hammer Require Import Hammer.

Require Export NOrder.

Module NAddOrderProp (Import N : NAxiomsMiniSig').
Include NOrderProp N.

Theorem le_add_r : forall n m, n <= n + m.
Proof. hammer_hook "NAddOrder" "NAddOrder.NAddOrderProp.le_add_r".
intro n; induct m.
rewrite add_0_r; now apply eq_le_incl.
intros m IH. rewrite add_succ_r; now apply le_le_succ_r.
Qed.

Theorem lt_lt_add_r : forall n m p, n < m -> n < m + p.
Proof. hammer_hook "NAddOrder" "NAddOrder.NAddOrderProp.lt_lt_add_r".
intros n m p H; rewrite <- (add_0_r n).
apply add_lt_le_mono; [assumption | apply le_0_l].
Qed.

Theorem lt_lt_add_l : forall n m p, n < m -> n < p + m.
Proof. hammer_hook "NAddOrder" "NAddOrder.NAddOrderProp.lt_lt_add_l".
intros n m p; rewrite add_comm; apply lt_lt_add_r.
Qed.

Theorem add_pos_l : forall n m, 0 < n -> 0 < n + m.
Proof. hammer_hook "NAddOrder" "NAddOrder.NAddOrderProp.add_pos_l".
intros; apply add_pos_nonneg. assumption. apply le_0_l.
Qed.

Theorem add_pos_r : forall n m, 0 < m -> 0 < n + m.
Proof. hammer_hook "NAddOrder" "NAddOrder.NAddOrderProp.add_pos_r".
intros; apply add_nonneg_pos. apply le_0_l. assumption.
Qed.

End NAddOrderProp.


(* This file is generated by Why3's Coq driver *)
(* Beware! Only edit allowed sections below    *)
Require Import ZArith.
Require Import Rbase.
Require int.Int.

Parameter bag : forall (a:Type), Type.

Parameter nb_occ: forall (a:Type), a -> (bag a) -> Z.
Implicit Arguments nb_occ.

Axiom occ_non_negative : forall (a:Type), forall (b:(bag a)) (x:a),
  (0%Z <= (nb_occ x b))%Z.

(* Why3 assumption *)
Definition mem (a:Type)(x:a) (b:(bag a)): Prop := (0%Z <  (nb_occ x b))%Z.
Implicit Arguments mem.

(* Why3 assumption *)
Definition eq_bag (a:Type)(a1:(bag a)) (b:(bag a)): Prop := forall (x:a),
  ((nb_occ x a1) = (nb_occ x b)).
Implicit Arguments eq_bag.

Axiom bag_extensionality : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),
  (eq_bag a1 b) -> (a1 = b).

Parameter empty_bag: forall (a:Type), (bag a).
Set Contextual Implicit.
Implicit Arguments empty_bag.
Unset Contextual Implicit.

Axiom occ_empty : forall (a:Type), forall (x:a), ((nb_occ x (empty_bag :(bag
  a))) = 0%Z).

Axiom is_empty : forall (a:Type), forall (b:(bag a)), (forall (x:a),
  ((nb_occ x b) = 0%Z)) -> (b = (empty_bag :(bag a))).

Parameter singleton: forall (a:Type), a -> (bag a).
Implicit Arguments singleton.

Axiom occ_singleton : forall (a:Type), forall (x:a) (y:a), ((x = y) /\
  ((nb_occ y (singleton x)) = 1%Z)) \/ ((~ (x = y)) /\ ((nb_occ y
  (singleton x)) = 0%Z)).

Axiom occ_singleton_eq : forall (a:Type), forall (x:a) (y:a), (x = y) ->
  ((nb_occ y (singleton x)) = 1%Z).

Axiom occ_singleton_neq : forall (a:Type), forall (x:a) (y:a), (~ (x = y)) ->
  ((nb_occ y (singleton x)) = 0%Z).

Parameter union: forall (a:Type), (bag a) -> (bag a) -> (bag a).
Implicit Arguments union.

Axiom occ_union : forall (a:Type), forall (x:a) (a1:(bag a)) (b:(bag a)),
  ((nb_occ x (union a1 b)) = ((nb_occ x a1) + (nb_occ x b))%Z).

Axiom Union_comm : forall (a:Type), forall (a1:(bag a)) (b:(bag a)),
  ((union a1 b) = (union b a1)).

Axiom Union_identity : forall (a:Type), forall (a1:(bag a)), ((union a1
  (empty_bag :(bag a))) = a1).

(* Why3 goal *)
Theorem Union_assoc : forall (a:Type), forall (a1:(bag a)) (b:(bag a))
  (c:(bag a)), ((union a1 (union b c)) = (union (union a1 b) c)).
(* YOU MAY EDIT THE PROOF BELOW *)
intros X a b c.
apply bag_extensionality; intro x.
do 4 rewrite occ_union; auto with zarith.
Qed.


(* @Owner MattIrv *)

Require Export QArith.
Require Export String.

Module BinStringToQ.

Inductive sign :=
  | sZero: sign
  | sPos: sign
  | sNeg: sign.

Local Open Scope char_scope.

Fixpoint bin_str_to_pos (str: string) (cp: positive) (start: bool) :=
  match start with
    | true =>
      match str with
        | EmptyString => None
        | String char s' =>
          match char with
            | "0" => bin_str_to_pos s' xH true
            | "1" => bin_str_to_pos s' xH false
            | _ => None
          end
      end
    | false =>
      match str with
        | EmptyString => Some cp
        | String char s' =>
          match char with
            | "0" => bin_str_to_pos s' (xO cp) false
            | "1" => bin_str_to_pos s' (xI cp) false
            | _ => None
          end
      end
  end.

Local Close Scope char_scope.

Definition numstr_to_z (numStr: string) (s: sign) :=
  match s with
    | sZero => Some Z0
    | sPos => let somepos := bin_str_to_pos numStr xH true in
      match somepos with
        | Some p => Some (Zpos p)
        | None => None
      end
    | sNeg => let somepos := bin_str_to_pos numStr xH true in
      match somepos with
        | Some p => Some (Zneg p)
        | None => None
      end
  end.

Definition bin_str_to_q (numStr denStr: string) (s: sign) :=
  let num := numstr_to_z numStr s in
  let denom := bin_str_to_pos denStr xH true in
    match num, denom with
      | None, _ => None
      | _, None => None
      | Some z, Some p => Some (Qmake z p)
    end.

Local Open Scope char_scope.

Fixpoint hex_str_to_bin_str (hexstr: string) :=
  match hexstr with
    | EmptyString => EmptyString
    | String char s' =>
      match char with
        | "0" => "0000" ++ hex_str_to_bin_str s'
        | "1" => "0001" ++ hex_str_to_bin_str s'
        | "2" => "0010" ++ hex_str_to_bin_str s'
        | "3" => "0011" ++ hex_str_to_bin_str s'
        | "4" => "0100" ++ hex_str_to_bin_str s'
        | "5" => "0101" ++ hex_str_to_bin_str s'
        | "6" => "0110" ++ hex_str_to_bin_str s'
        | "7" => "0111" ++ hex_str_to_bin_str s'
        | "8" => "1000" ++ hex_str_to_bin_str s'
        | "9" => "1001" ++ hex_str_to_bin_str s'
        | "A" => "1010" ++ hex_str_to_bin_str s'
        | "B" => "1011" ++ hex_str_to_bin_str s'
        | "C" => "1100" ++ hex_str_to_bin_str s'
        | "D" => "1101" ++ hex_str_to_bin_str s'
        | "E" => "1110" ++ hex_str_to_bin_str s'
        | "F" => "1111" ++ hex_str_to_bin_str s'
        | _ => "ERROR"%string
      end
  end
where "s1 ++ s2" := (append s1 s2).

Local Close Scope char_scope.

Definition hex_str_to_q (numStr denStr: string) (s: sign) :=
  let numBin := hex_str_to_bin_str numStr in
  let denBin := hex_str_to_bin_str denStr in
  bin_str_to_q numBin denBin s.

Example e1 := bin_str_to_q "0100101" "101010" sPos.
Example e2 := bin_str_to_q "0" "1" sPos.
Example e3 := bin_str_to_q "1" "10" sNeg.
Example h1 := hex_str_to_bin_str "2A".

End BinStringToQ.

Export BinStringToQ.


From Hammer Require Import Hammer.

Section Inverse_Image.

Variables A B : Type.
Variable R : B -> B -> Prop.
Variable f : A -> B.

Let Rof (x y:A) : Prop := R (f x) (f y).

Remark Acc_lemma : forall y:B, Acc R y -> forall x:A, y = f x -> Acc Rof x.
Proof. hammer_hook "Inverse_Image" "Inverse_Image.Acc_lemma".
induction 1 as [y _ IHAcc]; intros x H.
apply Acc_intro; intros y0 H1.
apply (IHAcc (f y0)); try trivial.
rewrite H; trivial.
Qed.

Lemma Acc_inverse_image : forall x:A, Acc R (f x) -> Acc Rof x.
Proof. hammer_hook "Inverse_Image" "Inverse_Image.Acc_inverse_image".
intros; apply (Acc_lemma (f x)); trivial.
Qed.

Theorem wf_inverse_image : well_founded R -> well_founded Rof.
Proof. hammer_hook "Inverse_Image" "Inverse_Image.wf_inverse_image".
red; intros; apply Acc_inverse_image; auto.
Qed.

Variable F : A -> B -> Prop.
Let RoF (x y:A) : Prop :=
exists2 b : B, F x b & (forall c:B, F y c -> R b c).

Lemma Acc_inverse_rel : forall b:B, Acc R b -> forall x:A, F x b -> Acc RoF x.
Proof. hammer_hook "Inverse_Image" "Inverse_Image.Acc_inverse_rel".
induction 1 as [x _ IHAcc]; intros x0 H2.
constructor; intros y H3.
destruct H3.
apply (IHAcc x1); auto.
Qed.

Theorem wf_inverse_rel : well_founded R -> well_founded RoF.
Proof. hammer_hook "Inverse_Image" "Inverse_Image.wf_inverse_rel".
red; constructor; intros.
case H0; intros.
apply (Acc_inverse_rel x); auto.
Qed.

End Inverse_Image.


From Hammer Require Import Hammer.

Require Import Decidable PeanoNat.
Require Eqdep_dec.
Local Open Scope nat_scope.

Implicit Types m n x y : nat.

Theorem O_or_S n : {m : nat | S m = n} + {0 = n}.
Proof. hammer_hook "Peano_dec" "Peano_dec.O_or_S".
induction n.
- now right.
- left; exists n; auto.
Defined.

Notation eq_nat_dec := Nat.eq_dec (compat "8.4").

Hint Resolve O_or_S eq_nat_dec: arith.

Theorem dec_eq_nat n m : decidable (n = m).
Proof. hammer_hook "Peano_dec" "Peano_dec.dec_eq_nat".
elim (Nat.eq_dec n m); [left|right]; trivial.
Defined.

Definition UIP_nat:= Eqdep_dec.UIP_dec Nat.eq_dec.

Import EqNotations.

Lemma le_unique: forall m n (le_mn1 le_mn2 : m <= n), le_mn1 = le_mn2.
Proof. hammer_hook "Peano_dec" "Peano_dec.le_unique".
intros m n.
generalize (eq_refl (S n)).
generalize n at -1.
induction (S n) as [|n0 IHn0]; try discriminate.
clear n; intros n [= <-] le_mn1 le_mn2.
pose (def_n2 := eq_refl n0); transitivity (eq_ind _ _ le_mn2 _ def_n2).
2: reflexivity.
generalize def_n2; revert le_mn1 le_mn2.
generalize n0 at 1 4 5 7; intros n1 le_mn1.
destruct le_mn1; intros le_mn2; destruct le_mn2.
+ now intros def_n0; rewrite (UIP_nat _ _ def_n0 eq_refl).
+ intros def_n0; generalize le_mn2; rewrite <-def_n0; intros le_mn0.
now destruct (Nat.nle_succ_diag_l _ le_mn0).
+ intros def_n0; generalize le_mn1; rewrite def_n0; intros le_mn0.
now destruct (Nat.nle_succ_diag_l _ le_mn0).
+ intros def_n0. injection def_n0 as ->.
rewrite (UIP_nat _ _ def_n0 eq_refl); simpl.
assert (H : le_mn1 = le_mn2).
now apply IHn0.
now rewrite H.
Qed.

Require Import Le Lt.


(** * Basics: Functional Programming in Coq *)

(*
   [Admitted] is Coq's "escape hatch" that says accept this definition
   without proof.  We use it to mark the 'holes' in the development
   that should be completed as part of your homework exercises.  In
   practice, [Admitted] is useful when you're incrementally developing
   large proofs. *)
Definition admit {T: Type} : T.  Admitted.

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

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

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

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

    The first half of this chapter introduces the most essential
    elements of Coq's functional programming language.  The second
    half introduces some basic _tactics_ that can be used to prove
    simple properties of Coq programs.
*)

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

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

    Naturally, the Coq distribution comes with an extensive standard
    library providing definitions of booleans, numbers, and many
    common data structures like lists and hash tables.  But there is
    nothing magic or primitive about these library definitions.  To
    illustrate this, we will explicitly recapitulate all the
    definitions we need in this course, rather than just getting them
    implicitly from the library.

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

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

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

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

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

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

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

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

(** Having defined a function, we should check that it works on
    some examples.  There are actually three different ways to do this
    in Coq.

    First, we can use the command [Compute] to evaluate a compound
    expression involving [next_weekday]. *)

Compute (next_weekday friday).
(* ==> monday : day *)

Compute (next_weekday (next_weekday saturday)).
(* ==> tuesday : day *)

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

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

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

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

Proof. simpl. reflexivity.  Qed.

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

(** Third, we can ask Coq to _extract_, from our [Definition], a
    program in some other, more conventional, programming
    language (OCaml, Scheme, or Haskell) with a high-performance
    compiler.  This facility is very interesting, since it gives us a
    way to construct _fully certified_ programs in mainstream
    languages.  Indeed, this is one of the main uses for which Coq was
    developed.  We'll come back to this topic in later chapters. *)

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

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

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

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

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

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

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

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

(** The last two illustrate Coq's syntax for multi-argument
    function definitions.  The corresponding multi-argument
    application syntax is illustrated by the following four "unit
    tests," which constitute a complete specification -- a truth
    table -- for the [orb] function: *)

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

(** We can also introduce some familiar syntax for the boolean
    operations we have just defined. The [Infix] command defines new,
    infix notation for an existing definition. *)

Infix "&&" := andb.
Infix "||" := orb.

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

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

(** The special phrases [Admitted] and [admit] can be used as a
    placeholder for an incomplete definition or proof.  We'll use them
    in exercises, to indicate the parts that we're leaving for you --
    i.e., your job is to replace [admit] or [Admitted] with real
    definitions or proofs. *)

(** **** Exercise: 1 star (nandb)  *)
(** Remove [admit] and complete the definition of the following
    function; then make sure that the [Example] assertions below can
    each be verified by Coq.  (Remove "[Admitted.]" and fill in each
    proof, following the model of the [orb] tests above.) The function
    should return [true] if either or both of its inputs are
    [false]. *)

Definition nandb (b1:bool) (b2:bool) : bool :=
  (* FILL IN HERE *) admit.

Example test_nandb1:               (nandb true false) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb2:               (nandb false false) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb3:               (nandb false true) = true.
(* FILL IN HERE *) Admitted.
Example test_nandb4:               (nandb true true) = false.
(* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star (andb3)  *)
(** Do the same for the [andb3] function below. This function should
    return [true] when all of its inputs are [true], and [false]
    otherwise. *)

Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
  (* FILL IN HERE *) admit.

Example test_andb31:                 (andb3 true true true) = true.
(* FILL IN HERE *) Admitted.
Example test_andb32:                 (andb3 false true true) = false.
(* FILL IN HERE *) Admitted.
Example test_andb33:                 (andb3 true false true) = false.
(* FILL IN HERE *) Admitted.
Example test_andb34:                 (andb3 true true false) = false.
(* FILL IN HERE *) Admitted.
(** [] *)

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

(** Every expression in Coq has a type, describing what sort of
    thing it computes. The [Check] command asks Coq to print the type
    of an expression. *)

(** For example, the type of [negb true] is [bool]. *)

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

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

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

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

(* ###################################################################### *)
(** ** Modules *)

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

Module Playground1.

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

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

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

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

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

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

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

(** The same rules apply for our definitions of [day] and
    [bool]. The annotations we used for their constructors are
    analogous to the one for the [O] constructor, indicating that they
    don't take any arguments. *)

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

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

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

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

End Playground1.

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

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

Check (S (S (S (S O)))).
  (* ===> 4 : nat *)
Compute (minustwo 4).
  (* ===> 2 : nat *)

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

Check S.
Check pred.
Check minustwo.

(** These are all things that can be applied to a number to yield a
    number.  However, there is a fundamental difference between the
    first one and the other two: functions like [pred] and [minustwo]
    come with _computation rules_ -- e.g., the definition of [pred]
    says that [pred 2] can be simplified to [1] -- while the
    definition of [S] has no such behavior attached.  Although it is
    like a function in the sense that it can be applied to an
    argument, it does not _do_ anything at all! *)

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

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

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

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

Example test_oddb1:    oddb 1 = true.
Proof. simpl. reflexivity.  Qed.
Example test_oddb2:    oddb 4 = false.
Proof. simpl. reflexivity.  Qed.

(** (You will notice if you step through these proofs that
    [simpl] actually has no effect on the goal -- all of the work is
    done by [reflexivity].  We'll see more about why that is
    shortly.)  *)

(** Naturally, we can also define multi-argument functions by
    recursion.   *)

Module Playground2.

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

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

Compute (plus 3 2).

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

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

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

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

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

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

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

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

End Playground2.

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

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

Fixpoint factorial (n:nat) : nat :=
(* FILL IN HERE *) admit.

Example test_factorial1:          (factorial 3) = 6.
(* FILL IN HERE *) Admitted.
Example test_factorial2:          (factorial 5) = (mult 10 12).
(* FILL IN HERE *) Admitted.

(** [] *)

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

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

Check ((0 + 1) + 1).

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

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

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

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

(** The [leb] function tests natural numbers for inequality, yielding
    a boolean. *)

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

Example test_leb1:             (leb 2 2) = true.
Proof. simpl. reflexivity.  Qed.
Example test_leb2:             (leb 2 4) = true.
Proof. simpl. reflexivity.  Qed.
Example test_leb3:             (leb 4 2) = false.
Proof. simpl. reflexivity.  Qed.

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

Definition blt_nat (n m : nat) : bool :=
  (* FILL IN HERE *) admit.

Example test_blt_nat1:             (blt_nat 2 2) = false.
(* FILL IN HERE *) Admitted.
Example test_blt_nat2:             (blt_nat 2 4) = true.
(* FILL IN HERE *) Admitted.
Example test_blt_nat3:             (blt_nat 4 2) = false.
(* FILL IN HERE *) Admitted.

(** [] *)

(* ###################################################################### *)
(** * Proof by Simplification *)

(** Now that we've defined a few datatypes and functions, let's
    turn to stating and proving properties of their behavior.
    Actually, we've already started doing this: each [Example] in the
    previous sections makes a precise claim about the behavior of some
    function on some particular inputs.  The proofs of these claims
    were always the same: use [simpl] to simplify both sides of the
    equation, then use [reflexivity] to check that both sides contain
    identical values.

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

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

(** (You may notice that the above statement looks different in
    the [.v] file in your IDE than it does in the HTML rendition in
    your browser, if you are viewing both. In [.v] files, we write the
    [forall] universal quantifier using the reserved identifier
    "forall."  When the [.v] files are converted to HTML, this gets
    transformed into an upside-down-A symbol.)  *)

(** This is a good place to mention that [reflexivity] is a bit
    more powerful than we have admitted. In the examples we have seen,
    the calls to [simpl] were actually not needed, because
    [reflexivity] can perform some simplification automatically when
    checking that two sides are equal; [simpl] was just added so that
    we could see the intermediate state -- after simplification but
    before finishing the proof.  Here is a shorter proof of the
    theorem: *)

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

(** Moreover, it will be useful later to know that [reflexivity]
    does somewhat _more_ simplification than [simpl] does -- for
    example, it tries "unfolding" defined terms, replacing them with
    their right-hand sides.  The reason for this difference is that,
    if reflexivity succeeds, the whole goal is finished and we don't
    need to look at whatever expanded expressions [reflexivity] has
    created by all this simplification and unfolding; by contrast,
    [simpl] is used in situations where we may have to read and
    understand the new goal that it creates, so we would not want it
    blindly expanding definitions and leaving the goal in a messy
    state. *)

(** The form of the theorem we just stated and its proof are
    almost exactly the same as the simpler examples we saw earlier;
    there are just a few differences.

    First, we've used the keyword [Theorem] instead of [Example].
    This difference is purely a matter of style; the keywords
    [Example] and [Theorem] (and a few others, including [Lemma],
    [Fact], and [Remark]) mean exactly the same thing to Coq.

    Second, we've added the quantifier [forall n:nat], so that our
    theorem talks about _all_ natural numbers [n].  In order to prove
    theorems of this form, we need to to be able to reason by
    _assuming_ the existence of an arbitrary natural number [n].  This
    is achieved in the proof by [intros n], which moves the quantifier
    from the goal to a _context_ of current assumptions. In effect, we
    start the proof by saying "Suppose [n] is some arbitrary
    number..."

    The keywords [intros], [simpl], and [reflexivity] are examples of
    _tactics_.  A tactic is a command that is used between [Proof] and
    [Qed] to guide the process of checking some claim we are making.
    We will see several more tactics in the rest of this chapter and
    yet more in future chapters.

    Other similar theorems can be proved with the same pattern. *)

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

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

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

(** It is worth stepping through these proofs to observe how the
context and the goal change. *)
(** You may want to add calls to [simpl] before [reflexivity] to
see the simplifications that Coq performs on the terms before checking
that they are equal. *)

(** Although simplification is powerful enough to prove some
    fairly general facts, there are many statements that cannot be
    handled by simplification alone.  For instance, we cannot use it
    to prove that [0] is also a neutral element for [+] _on the
    right_. *)

Theorem plus_n_O : forall n, n + 0 = n.
Proof.
  intros n. simpl. (* Doesn't do anything! *)

(** (Can you explain why this happens?  Step through both proofs
    with Coq and notice how the goal and context change.)

    When stuck in the middle of a proof, we can use the [Abort]
    command to give up on it for the moment. *)

Abort.

(** The next chapter will introduce _induction_, a powerful
    technique that can be used for proving this goal.  For the moment,
    though, let's look at a few more simple tactics. *)

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

(** This theorem is a bit more interesting than the others we've
    seen: *)

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

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

    As before, we need to be able to reason by assuming the existence
    of some numbers [n] and [m].  We also need to assume the hypothesis
    [n = m]. The [intros] tactic will serve to move all three of these
    from the goal into assumptions in the current context.

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

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

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

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

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

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

(** **** Exercise: 2 stars (mult_S_1)  *)
Theorem mult_S_1 : forall n m : nat,
  m = S n ->
  m * (1 + n) = m * m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

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

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

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

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

(** The [destruct] generates _two_ subgoals, which we must then
    prove, separately, in order to get Coq to accept the theorem. The
    annotation "[as [| n']]" is called an _intro pattern_.  It tells
    Coq what variable names to introduce in each subgoal.  In general,
    what goes between the square brackets is a _list of lists_ of
    names, separated by [|].  In this case, the first component is
    empty, since the [O] constructor is nullary (it doesn't have any
    arguments).  The second component gives a single name, [n'], since
    [S] is a unary constructor.

    The [-] signs on the second and third lines are called _bullets_,
    and they mark the parts of the proof that correspond to each
    generated subgoal.  The proof script that comes after a bullet is
    the entire proof for a subgoal.  In this example, each of the
    subgoals is easily proved by a single use of [reflexivity], which
    itself performs some simplification -- e.g., the first one
    simplifies [beq_nat (S n' + 1) 0] to [false] by first rewriting
    [(S n' + 1)] to [S (n' + 1)], then unfolding [beq_nat], and then
    simplifying the [match].

    Marking cases with bullets is entirely optional: if bullets are
    not present, Coq simply asks you to prove each subgoal in
    sequence, one at a time. But it is a good idea to use bullets.
    For one thing, they make the structure of a proof apparent, making
    it more readable. Also, bullets instruct Coq to ensure that a
    subgoal is complete before trying to verify the next one,
    preventing proofs for different subgoals from getting mixed
    up. These issues become especially important in large
    developments, where fragile proofs lead to long debugging
    sessions.

    There are no hard and fast rules for how proofs should be
    formatted in Coq -- in particular, where lines should be broken
    and how sections of the proof should be indented to indicate their
    nested structure.  However, if the places where multiple subgoals
    are generated are marked with explicit bullets at the beginning of
    lines, then the proof will be readable almost no matter what
    choices are made about other aspects of layout.

    This is also a good place to mention one other piece of somewhat
    obvious advice about line lengths.  Beginning Coq users sometimes
    tend to the extremes, either writing each tactic on its own line
    or writing entire proofs on one line.  Good style lies somewhere
    in the middle.  One reasonable convention is to limit yourself to
    80-character lines.

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

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

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

    It is sometimes useful to invoke [destruct] inside a subgoal,
    generating yet more proof obligations. In this case, we use
    different kinds of bullets to mark goals on different "levels."
    For example: *)

Theorem andb_commutative : forall b c, andb b c = andb c b.
Proof.
  intros b c. destruct b.
  - destruct c.
    + reflexivity.
    + reflexivity.
  - destruct c.
    + reflexivity.
    + reflexivity.
Qed.

(** Each pair of calls to [reflexivity] corresponds to the
    subgoals that were generated after the execution of the [destruct
    c] line right above it.  Besides [-] and [+], Coq proofs can also
    use [*] (asterisk) as a third kind of bullet. If we ever encounter
    a proof that generates more than three levels of subgoals, we can
    also enclose individual subgoals in curly braces ([{ ... }]): *)

Theorem andb_commutative' : forall b c, andb b c = andb c b.
Proof.
  intros b c. destruct b.
  { destruct c.
    { reflexivity. }
    { reflexivity. } }
  { destruct c.
    { reflexivity. }
    { reflexivity. } }
Qed.

(** Since curly braces mark both the beginning and the end of a
    proof, they can be used for multiple subgoal levels, as this
    example shows. Furthermore, curly braces allow us to reuse the
    same bullet shapes at multiple levels in a proof: *)

Theorem andb3_exchange :
  forall b c d, andb (andb b c) d = andb (andb b d) c.
Proof.
  intros b c d. destruct b.
  - destruct c.
    { destruct d.
      - reflexivity.
      - reflexivity. }
    { destruct d.
      - reflexivity.
      - reflexivity. }
  - destruct c.
    { destruct d.
      - reflexivity.
      - reflexivity. }
    { destruct d.
      - reflexivity.
      - reflexivity. }
Qed.

(** Before closing the chapter, let's mention one final
    convenience.  As you may have noticed, many proofs perform case
    analysis on a variable right after introducing it:
  intros x y. destruct y as [|y].
    This pattern is so common that Coq provides a shorthand for it: we
    can perform case analysis on a variable when introducing it by
    using an intro pattern instead of a variable name. For instance,
    here is a shorter proof of the [plus_1_neq_0] theorem above. *)

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

(** If there are no arguments to name, we can just write [[]]. *)

Theorem andb_commutative'' :
  forall b c, andb b c = andb c b.
Proof.
  intros [] [].
  - reflexivity.
  - reflexivity.
  - reflexivity.
  - reflexivity.
Qed.

(** **** Exercise: 2 stars (andb_true_elim2)  *)
(** Prove the following claim, marking cases (and subcases) with
    bullets when you use [destruct]. *)

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star (zero_nbeq_plus_1)  *)
Theorem zero_nbeq_plus_1 : forall n : nat,
  beq_nat 0 (n + 1) = false.
Proof.
  (* FILL IN HERE *) Admitted.

(** [] *)

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

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

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof.
  (* FILL IN HERE *) Admitted.

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

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

(** **** Exercise: 2 stars (andb_eq_orb)  *)
(** Prove the following theorem.  (You may want to first prove a
    subsidiary lemma or two. Alternatively, remember that you do
    not have to introduce all hypotheses at the same time.) *)

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (binary)  *)
(** Consider a different, more efficient representation of natural
    numbers using a binary rather than unary system.  That is, instead
    of saying that each natural number is either zero or the successor
    of a natural number, we can say that each binary number is either

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

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

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

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

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

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

(* ###################################################################### *)
(** ** More on Notation (Optional) *)

(** (In general, sections marked Optional are not needed to follow the
    rest of the book, except possibly other Optional sections.  On a
    first reading, you might want to skim these sections so that you
    know what's there for future reference.) *)

(** Recall the notation definitions for infix plus and times: *)

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

(** For each notation symbol in Coq, we can specify its _precedence
    level_ and its _associativity_.  The precedence level [n] is
    specified by writing [at level n]; this helps Coq parse compound
    expressions.  The associativity setting helps to disambiguate
    expressions containing multiple occurrences of the same
    symbol. For example, the parameters specified above for [+] and
    [*] say that the expression [1+2*3*4] is shorthand for
    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and
    _left_, _right_, or _no_ associativity.  We will see more examples
    of this later, e.g., in the [Lists] chapter.

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

    Notation scopes also apply to numeral notation ([3], [4], [5],
    etc.), so you may sometimes see [0%nat], which means [O] (the
    natural number [0] that we're using in this chapter), or [0%Z],
    which means the Integer zero (which comes from a different part of
    the standard library). *)

(** ** Fixpoints and Structural Recursion (Optional) *)

(** Here is a copy of the definition of addition: *)

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

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

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

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

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

(** $Date: 2016-01-13 14:17:28 -0500 (Wed, 13 Jan 2016) $ *)


Set Implicit Arguments.

Require Import Coq.Lists.List.

Section TopSection.

  Fixpoint app_all A (ls : list (list A)) :=
    match ls with
      | nil => nil
      | x :: xs => x ++ app_all xs
    end.

  Definition Disjoint A (ls1 ls2 : list A) := forall e : A, ~ (In e ls1 /\ In e ls2).

  Definition IsInjection A B (f : A -> B) := forall x y, x <> y -> f x <> f y.

  Definition Injective A B (f : A -> B) := forall x1 x2, f x1 = f x2 -> x1 = x2.

  Lemma Injective_IsInjection A B (f : A -> B) : Injective f -> IsInjection f.
  Proof.
    unfold Injective, IsInjection in *; intuition.
  Qed.

  Variable t : Type.
  Variable B : Type.

  Implicit Types ls : list t.
  Implicit Types f : t -> B.
  Implicit Types x y e a : t.

  Lemma map_app_all : forall f lsls, map f (app_all lsls) = app_all (map (fun ls => map f ls) lsls).
    induction lsls; simpl; intros; eauto.
    rewrite map_app; f_equal; eauto.
  Qed.

  Require Import Coq.Bool.Sumbool.
  Require Import Platform.Cito.GeneralTactics.

  Lemma find_spec : forall (f : t -> bool) ls a, find f ls = Some a -> f a = true /\ In a ls.
    induction ls; simpl; intuition; try discriminate;
    (destruct (sumbool_of_bool (f a));
     [rewrite e in H; injection H; intros; subst; eauto |
      rewrite e in H; eapply IHls in H; openhyp; eauto]).
  Qed.

  Lemma find_spec_None : forall (f : t -> bool) ls, List.find f ls = None -> ~ exists a, List.In a ls /\ f a = true.
    induction ls; simpl; intuition.
    openhyp; intuition.
    openhyp.
    subst.
    rewrite H1 in H.
    intuition.
    eapply IHls.
    discriminate.
    discriminate.
    destruct (f a); intuition.
    discriminate.
    eapply H2.
    eexists; split; eauto.
  Qed.

  Lemma In_app_all_intro : forall lsls ls e, In e ls -> In ls lsls -> In e (app_all lsls).
    induction lsls; simpl; intros.
    eauto.
    openhyp.
    subst.
    eapply in_or_app.
    eauto.
    eapply in_or_app.
    right.
    eauto.
  Qed.

  Lemma In_app_all_elim : forall lsls x, In x (app_all lsls) -> exists ls, In x ls /\ In ls lsls.
    induction lsls; simpl; intros.
    intuition.
    eapply in_app_or in H.
    openhyp.
    eexists.
    eauto.
    eapply IHlsls in H.
    openhyp.
    eexists; eauto.
  Qed.

  Lemma Disjoint_symm : forall ls1 ls2, Disjoint ls1 ls2 -> Disjoint ls2 ls1.
    unfold Disjoint; intros; firstorder.
  Qed.

  Lemma Disjoint_incl : forall ls1 ls2 ls1' ls2', Disjoint ls1 ls2 -> incl ls1' ls1 -> incl ls2' ls2 -> Disjoint ls1' ls2'.
    unfold Disjoint, incl; intros; firstorder.
  Qed.

  Lemma incl_map : forall f ls1 ls2, incl ls1 ls2 -> incl (map f ls1) (map f ls2).
    unfold incl.
    intros.
    eapply in_map_iff in H0.
    openhyp.
    subst.
    eapply H in H1.
    eapply in_map_iff.
    eexists.
    eauto.
  Qed.

  Lemma Disjoint_map : forall f ls1 ls2, Disjoint (map f ls1) (map f ls2) -> Disjoint ls1 ls2.
    unfold Disjoint; intros.
    intuition.
    eapply H.
    split; eapply in_map; eauto.
  Qed.

  Lemma Injection_NoDup : forall f ls, IsInjection f -> NoDup ls -> NoDup (map f ls).
    unfold IsInjection.
    induction ls; simpl; intros.
    econstructor.
    inversion H0; subst.
    econstructor.
    intuition.
    contradict H3.
    eapply in_map_iff in H1.
    openhyp.
    eapply H in H1.
    intuition.
    intros.
    subst.
    inversion H0; subst.
    contradiction.
    eapply IHls.
    eauto.
    eauto.
  Qed.

  Lemma NoDup_app : forall ls1 ls2, NoDup ls1 -> NoDup ls2 -> Disjoint ls1 ls2 -> NoDup (ls1 ++ ls2).
    unfold Disjoint.
    induction ls1; simpl; intros.
    eauto.
    econstructor.
    intuition.
    eapply in_app_or in H2.
    openhyp.
    inversion H; subst.
    contradiction.
    eapply H1.
    eauto.
    eapply IHls1.
    inversion H; subst.
    eauto.
    eauto.
    intros.
    firstorder.
  Qed.

End TopSection.

Require Import Coq.Bool.Bool.

Local Open Scope bool_scope.

Fixpoint forall2 A B (pred : A -> B -> bool) ls1 ls2 :=
  match ls1, ls2 with
    | a :: ls1', b :: ls2' => pred a b && forall2 pred ls1' ls2'
    | nil, nil => true
    | _, _ => false
  end.

Lemma forall2_sound A B pred (P : A -> B -> Prop) : (forall a b, pred a b = true -> P a b) -> forall ls1 ls2, forall2 pred ls1 ls2 = true -> List.Forall2 P ls1 ls2.
Proof.
  intros Hs.
  induction ls1; destruct ls2; simpl; try solve [intros; try discriminate; intuition].
  intros Hp; eapply andb_true_iff in Hp.
  openhyp; econstructor; eauto.
Qed.


Require Import ExtLib.Data.Fin.

Set Implicit Arguments.
Set Strict Implicit.
Set Asymmetric Patterns.

Fixpoint vector (T : Type) (n : nat) : Type :=
  match n with
    | 0 => unit
    | S n => prod T (vector T n)
  end.

Fixpoint get {T} {n : nat} (f : fin n) : vector T n -> T :=
  match f in fin n return vector T n -> T with
    | F0 n => fun v : T * vector T n => fst v
    | FS n f => fun v : T * vector T n => get f (snd v)
  end.

Fixpoint put {T} {n : nat} (f : fin n) (t : T) : vector T n -> vector T n :=
  match f in fin n return vector T n -> vector T n with
    | F0 _ => fun v => (t, snd v)
    | FS _ f => fun v => (fst v, put f t (snd v))
  end.

Theorem get_put_eq : forall {T n} (v : vector T n) (f : fin n) val,
  get f (put f val v) = val.
Proof.
  induction n.
  { inversion f. }
  { remember (S n). destruct f.
    inversion Heqn0; subst; intros; reflexivity.
    inversion Heqn0; subst; simpl; auto. }
Qed.

Theorem get_put_neq : forall {T n} (v : vector T n) (f f' : fin n) val,
  f <> f' ->
  get f (put f' val v) = get f v.
Proof.
  induction n.
  { inversion f. }
  { remember (S n); destruct f.
    { inversion Heqn0; clear Heqn0; subst; intros.
      destruct (fin_case f'); try congruence.
      destruct H0; subst. auto. }
    { inversion Heqn0; clear Heqn0; subst; intros.
      destruct (fin_case f').
      subst; auto.
      destruct H0; subst. simpl.
      eapply IHn. congruence. } }
Qed.

Definition vector_tl {T : Type} {n : nat} (v : vector T (S n)) : vector T n :=
  snd v.

Definition vector_hd {T : Type} {n : nat} (v : vector T (S n)) : T :=
  fst v.


Require Export Lists.

(** Insertion sort : algorithm.
    Here we define the implementation of insertion sort
    we'll be using. *)

(** Insert an element in its place in a sorted list.
   This is the main subroutine for insertion sort. *)
Fixpoint insert (v : nat) (l : natlist) : natlist :=
  match l with
  (* keep in mind that we're assuming l is sorted for this function
     to make sense *)
  | [] => [v]
  | h :: t => match ble_nat v h with
              | true => v :: h :: t
              | false => h :: (insert v t)
              end
  end.

(** This is the insertion sort algorithm: sort the tail
    recursively and insert the head. *)
Fixpoint insertion_sort (l : natlist) : natlist :=
  match l with
  | [] => []
  | h :: t => insert h (insertion_sort t)
  end.


Require Import Coq.Strings.String.
Require Import Coq.ZArith.ZArith.
Require Import Coq.micromega.Psatz.
Require Import SetsClass.SetsClass.
Require Import PV.Syntax.
Import Lang_While.
Require Import PV.PracticalDenotations.
Import DntSem_While.
Local Open Scope Z.
Local Open Scope sets.
Local Open Scope string.
Arguments Rels.concat: simpl never.

(** 习题：*)

(** 请证明以下两条关于_[Rels.test]_的性质。*)

Lemma Rels_test_empty: forall X: state -> Prop,
  X == ∅ ->
  Rels.test X == ∅.
Proof.
  unfold_RELS_tac.
  intros.
  sets_unfold in H.
  split.
  - intro.
    destruct H0.
    rewrite <- (H a).
    apply H0.
  - tauto.
Qed.

Lemma Rels_test_full: forall X: state -> Prop,
  X == Sets.full ->
  Rels.test X == Rels.id.
Proof.
  unfold_RELS_tac.
  intros.
  sets_unfold in H.
  split; intro.
  - destruct H0.
    apply H1.
  - split.
    + apply H.
      tauto.
    + tauto.
Qed.

(** 习题：*)

(** 请证明：如果循环条件恒为真且循环体的行为不改变程序状态，循环是不会终止的。 *)

Lemma inf_loop_nrm: forall e c n,
  test_true (eval_expr e) == Rels.id ->
  test_false (eval_expr e) == ∅ ->
  (eval_com c).(nrm) == Rels.id ->
  iter_nrm_lt_n (eval_expr e) (eval_com c) n == ∅.
Proof.
  intros.
  induction n; try reflexivity.
  simpl.
  rewrite H, H0, H1, IHn.
  rewrite ! Rels_concat_id_l.
  rewrite Sets_union_empty.
  reflexivity.
Qed.

(** 习题：*)

(** 请证明：如果循环条件恒为真且循环体的行为不改变程序状态，循环是不会运行出错的。 *)

Lemma inf_loop_err: forall e c n,
  test_true (eval_expr e) == Rels.id ->
  (eval_expr e).(err) == ∅ ->
  (eval_com c).(nrm) == Rels.id ->
  (eval_com c).(err) == ∅ ->
  iter_err_lt_n (eval_expr e) (eval_com c) n == ∅.
Proof.
  intros.
  revert n.
  induction n; try reflexivity.
  simpl.
  rewrite H, H0, H1, H2, IHn.
  rewrite ! Rels_concat_id_l.
  rewrite ! Sets_union_empty.
  reflexivity.
Qed.


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

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

Compute ( next_weekday friday ).

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

Proof. simpl. reflexivity. Qed.


Require Import List.
Import ListNotations.
Require Import Sorting.Permutation.

(**
  Lightly adapted from Coq stdlib mergesort to not be a functor.
*)

Section Sorting.
  Variable t : Type.
  Variable le : t -> t -> bool.

  Variable le_reflexive :
    forall x, le x x = true.

  Variable le_transitive :
    forall x y z,
      le x y = true ->
      le y z = true ->
      le x z = true.

  Variable le_total :
    forall x y,
      le x y = true \/ le y x = true.

  Inductive sorted : list t -> Prop :=
  | SortedNil :
      sorted []
  | SortedSingleton :
      forall x, sorted [x]
  | SortedCons :
      forall x y l,
        sorted (y :: l) ->
        le x y = true ->
        sorted (x :: y :: l).

  (* from Coq stdlib mergesort implementation *)
  Fixpoint merge l1 l2 :=
    let fix merge_aux l2 :=
        match l1, l2 with
        | [], _ => l2
        | _, [] => l1
        | a1::l1', a2::l2' =>
          if le a1 a2
          then a1 :: merge l1' l2
          else a2 :: merge_aux l2'
        end
    in merge_aux l2.

  Definition tstack : Type := list (option (list t)).

  (* from Coq stdlib mergesort implementation *)
  Fixpoint merge_list_to_stack (stack : tstack) (l : list t) : tstack :=
    match stack with
    | [] => [Some l]
    | None :: stack' => Some l :: stack'
    | Some l' :: stack' => None :: merge_list_to_stack stack' (merge l' l)
    end.

  (* from Coq stdlib mergesort implementation *)
  Fixpoint merge_stack (stack : tstack) : list t :=
    match stack with
    | [] => []
    | None :: stack' => merge_stack stack'
    | Some l :: stack' => merge l (merge_stack stack')
    end.

  (* from Coq stdlib mergesort implementation *)
  Fixpoint iter_merge (stack : tstack) (l : list t) : list t :=
    match l with
    | [] => merge_stack stack
    | a::l' => iter_merge (merge_list_to_stack stack [a]) l'
    end.

  (* from Coq stdlib mergesort implementation *)
  Definition sort : list t -> list t :=
    iter_merge [].

  (* all proofs below from Coq stdlib mergesort implementation *)

  Local Ltac invert H := inversion H; subst; clear H.

  Fixpoint flatten_stack (stack : list (option (list t))) :=
    match stack with
    | [] => []
    | None :: stack' => flatten_stack stack'
    | Some l :: stack' => l ++ flatten_stack stack'
    end.

  Theorem Permuted_merge :
   forall l1 l2, Permutation (l1++l2) (merge l1 l2).
  Proof.
    induction l1; simpl merge; intro.
    - assert (forall l, (fix merge_aux (l0 : list t) : list t := l0) l = l)
      as -> by (destruct l; trivial). (* Technical lemma *)
      apply Permutation_refl.
    - induction l2.
      rewrite app_nil_r. apply Permutation_refl.
      destruct (le a a0).
        + constructor; apply IHl1.
        + apply Permutation_sym, Permutation_cons_app, Permutation_sym, IHl2.
  Qed.

  Theorem Permuted_merge_stack : forall stack,
    Permutation (flatten_stack stack) (merge_stack stack).
  Proof.
    induction stack as [|[]]; simpl.
    -  trivial.
    -  transitivity (l ++ merge_stack stack).
        + apply Permutation_app_head; trivial.
        + apply Permuted_merge.
    - assumption.
  Qed.

  Theorem Permuted_merge_list_to_stack :
    forall stack l,
      Permutation (l ++ flatten_stack stack)
                  (flatten_stack (merge_list_to_stack stack l)).
  Proof.
    induction stack as [|[]]; simpl; intros.
    - reflexivity.
    - rewrite app_assoc.
      etransitivity.
      + apply Permutation_app_tail.
        etransitivity.
        * apply Permutation_app_comm.
        * apply Permuted_merge.
      + apply IHstack.
    - reflexivity.
  Qed.

  Theorem Permuted_iter_merge : forall l stack,
    Permutation (flatten_stack stack ++ l) (iter_merge stack l).
  Proof.
    induction l; simpl; intros.
    - rewrite app_nil_r. apply Permuted_merge_stack.
    - change (a::l) with ([a]++l).
      rewrite app_assoc.
      etransitivity.
      +  apply Permutation_app_tail.
         etransitivity.
         apply Permutation_app_comm.
         apply Permuted_merge_list_to_stack.
      + apply IHl.
  Qed.

  Theorem sort_permutes :
    forall l l',
      l' = sort l ->
      Permutation l l'.
  Proof.
    intros; subst; apply (Permuted_iter_merge l []).
  Qed.

  Fixpoint sorted_stack stack :=
  match stack with
  | [] => True
  | None :: stack' => sorted_stack stack'
  | Some l :: stack' => sorted l /\ sorted_stack stack'
  end.

  Theorem sorted_merge : forall l1 l2,
      sorted l1 -> sorted l2 -> sorted (merge l1 l2).
  Proof.
    induction l1; induction l2; intros; simpl; auto.
    destruct (le a a0) eqn:Heq1.
    - invert H.
      simpl. constructor; trivial; rewrite Heq1; constructor.
      assert (sorted (merge (y::l) (a0::l2))) by (apply IHl1; auto).
      clear H0 H3 IHl1; simpl in *.
      destruct (le y a0); constructor; auto || rewrite Heq1; constructor.
    - assert (le a0 a = true).
        (destruct (le_total a0 a)); auto.
        rewrite H1 in Heq1.
        congruence.
      invert H0.
      constructor; trivial.
      assert (sorted (merge (a::l1) (y::l))) by auto using IHl1.
      clear IHl2; simpl in *.
      destruct (le a y); constructor; auto.
  Qed.

  Theorem sorted_merge_stack : forall stack,
      sorted_stack stack -> sorted (merge_stack stack).
  Proof.
    induction stack as [|[|]]; simpl; intros.
    constructor; auto.
    apply sorted_merge; tauto.
    auto.
  Qed.

  Theorem sorted_merge_list_to_stack : forall stack l,
      sorted_stack stack -> sorted l -> sorted_stack (merge_list_to_stack stack l).
  Proof.
  induction stack as [|[|]]; intros; simpl.
    auto.
    apply IHstack. destruct H as (_,H1). fold sorted_stack in H1. auto.
      apply sorted_merge; auto; destruct H; auto.
      auto.
  Qed.

  Theorem sorted_iter_merge : forall stack l,
      sorted_stack stack -> sorted (iter_merge stack l).
  Proof.
    intros stack l H; induction l in stack, H |- *; simpl.
    auto using sorted_merge_stack.
    assert (sorted [a]) by constructor.
    auto using sorted_merge_list_to_stack.
  Qed.

  Theorem sorted_sort : forall l, sorted (sort l).
  Proof.
    intro; apply sorted_iter_merge. constructor.
  Qed.
End Sorting.