From mathcomp Require Import ssreflect ssrbool ssrnat ssrfun eqtype.

(* Three Color Triangle Problem (TCTP) *)
Section TCTP_definitions.
  (* Color: the type for the three colors in TCTP *)
  (* red, blu (=blue), and yel (=yellow) *)
  Inductive Color : Set := red | yel | blu.

  (* The mix operation produces a next color by mixing two given colors *)
  Definition mix c0 c1 :=
    match c0, c1 with
    | red, red => red
    | red, yel => blu
    | red, blu => yel
    | yel, red => blu
    | yel, yel => yel
    | yel, blu => red
    | blu, red => yel
    | blu, yel => red
    | blu, blu => blu
    end.
  Lemma mixcut c0 c1 c2 c3: mix (mix (mix c0 c1) (mix c1 c2)) (mix (mix c1 c2) (mix c2 c3)) = mix c0 c3.
  Proof. by move: c0 c1 c2 c3 => [] [] [] []. Qed.

  Definition coloring := nat -> nat -> Color.

  (* Meaning: The color of the node (x,y+1) is the mixure of those of the nodes (x,y) and (x+1,y). *)
  Definition CFun colfun := forall x y, colfun x y.+1 = mix (colfun x y) (colfun x.+1 y).

  (* Meaning: The color of the node (x,y+n) is the mixure of those of the nodes (x,y) and (x+n,y). *)
  Definition WellColoredVertices colfun x y n := colfun x (y + n) = mix (colfun x y) (colfun (x + n) y).

  (* Meaning: The triangle (x,0)-(x+n,0)-(x,n) makes a well-colored triangle for any expected coloring. *)
  Definition WellColoredTriangle x y n := forall colfun, CFun colfun -> WellColoredVertices colfun x y n.

  (* Lifting of top-level coloring functions (This will be applied to coloringYBBY and coloringBYB defined later) *)
  Fixpoint liftcoloring (topcoloring : nat -> Color) x y :=
    if y is y'.+1 then mix (liftcoloring topcoloring x y') (liftcoloring topcoloring x.+1 y') else topcoloring x.
End TCTP_definitions.

Section TCTP.
(* Proof of the sufficient conditions ------------------------------------*)
  Theorem TCTP_suf (k x y : nat) : WellColoredTriangle x y (3 ^ k).
  Proof.
    move=> colfun H.
    elim: k x y => [|k IHk] x y; first by rewrite expn0 /WellColoredVertices !addn1; exact /H.
    rewrite /WellColoredVertices -(mixcut _ (colfun (x + 3 ^ k) y) (colfun (x + (3 ^ k).*2) y)).
    have <- : WellColoredVertices colfun x y (3 ^ k) by exact: IHk.
    rewrite -addnn addnA.
    have <- : WellColoredVertices colfun (x + 3 ^ k) y (3 ^ k) by exact: IHk.
    have <- : WellColoredVertices colfun x (y + 3 ^ k) (3  ^k) by exact: IHk.
    have -> : 3 ^ k.+1 = (3 ^ k).*2 + 3 ^ k by rewrite expnS (mulnDl 1 2) mul1n mul2n addnC.
    rewrite -!addnA addnn !addnA.
    have <- : WellColoredVertices colfun (x + (3 ^ k).*2) y (3 ^ k) by exact: IHk.
    rewrite -addnn !addnA.
    have <- : WellColoredVertices colfun (x + 3 ^ k) (y + 3 ^ k) (3 ^ k) by exact: IHk.
    rewrite -!addnA addnn !addnA.
    have <- : WellColoredVertices colfun x (y + (3 ^ k).*2) (3  ^k) by exact: IHk.
    by rewrite addnAC.
  Qed.

(* Proof of the necessary condition ------------------------------------*)
Section Allred.
  (* allred: The lower most cell is red if there is a line whose all cells are red *)
  Variables (colfun : coloring) (x y n : nat).
  Hypothesis H : CFun colfun.
  Hypothesis redline : forall i, i <= n -> colfun (x + i) y = red.

  Lemma allred : colfun x (y + n) = red.
  Proof.
    suff bottom q p : p + q <= n -> colfun (x + p) (y + q) = red by rewrite -(addn0 x); exact: bottom.
    elim: q p => [p|q IHq p pqn]; first by rewrite !addn0; apply redline.
    by rewrite addnS H IHq ?(leq_trans _ pqn)// -?addnS ?IHq// ?addnS// addSnnS.
  Qed.
End Allred.

(* Begin: TCTP_nec_even --------------------*)
(* coloringYB x n: paint cells from x to x+n alternatively (like yellow, blue, ..) (paint yellow for cells out of the range) *)
Definition coloringYB n i := if (i <= n) && ~~ odd i then yel else blu.

Section TCTP_nec_even.
Variables (colfun : coloring) (n : nat).
Hypotheses (n_gt_0 : n > 0) (H : CFun colfun).
Hypothesis topcolor : forall i, i <= n -> colfun i 0 = coloringYB n i.

Lemma even_bottom : colfun 0 n = red.
Proof.
  suff even_next_red i : i <= n.-1 -> colfun i 1 = red; first by rewrite -(prednK n_gt_0) -add1n allred//.
  move=> i_leq_pn.
  have i_leq_n : i <= n by rewrite (leq_trans i_leq_pn) // leq_pred.
  have i_lt_n : i < n by rewrite -add1n -leq_subRL ?subn1.
  have -> : colfun i 1 = mix (colfun i 0) (colfun i.+1 0); first exact/H.
  have -> : colfun i 0 = coloringYB n i by rewrite topcolor.
  have -> : colfun i.+1 0 = coloringYB n i.+1 by rewrite topcolor //.
  have YB_yel m j : j <= m -> ~~ odd j -> coloringYB m j = yel.
  by move=> m_gt_j oj; rewrite /coloringYB m_gt_j oj.
  have YB_blu m j : odd j -> coloringYB m j = blu by move=> oj; rewrite /coloringYB oj andbF.
  have [oi|ei] := boolP (odd i).
  - have -> : coloringYB n i = blu by exact: YB_blu.
    have ->// : coloringYB n i.+1 = yel by rewrite YB_yel //= oi.
  - have -> : coloringYB n i = yel by exact: YB_yel.
    have ->// : coloringYB n i.+1 = blu by exact: YB_blu.
Qed.
End TCTP_nec_even.

Lemma TCTP_nec_even n : n > 0 -> ~~ odd n -> ~ WellColoredTriangle 0 0 n.
Proof.
  move=> n_gt_0 en WCT.
  have H: CFun (liftcoloring (fun z => coloringYB n z)) by rewrite /=.
  have := WCT _ H; rewrite /WellColoredVertices addnC addn0.
  have <- : coloringYB n 0 = liftcoloring (fun z => coloringYB n z) 0 0 by rewrite//=.
  have <- : coloringYB n n = liftcoloring (fun z => coloringYB n z) n 0 by rewrite //=.
  have -> : coloringYB n 0 = yel by rewrite /=.
  have -> : coloringYB n n = yel by rewrite /coloringYB leqnn en.
  have -> // : liftcoloring (fun z => coloringYB n z) 0 n = red.
  exact: even_bottom => //.
Qed.

(* End: TCTP_nec_even --------------------*)

(* Begin: TCTP_nec_shortodd --------------------*)
Definition coloringYBBY n i := if ((i <= n./2) && odd i) || ((n./2.+1 <= i <= n) && ~~ odd i) then blu else yel.

(* Some properties of coloringYBBY *)
Lemma YBBY_yel_even n i : i <= n./2 -> ~~ odd i -> coloringYBBY n i = yel.
Proof. by move=> i_leq_hn /negbTE oi; rewrite /coloringYBBY oi /= !(andbF,andbT)/= ltnNge i_leq_hn. Qed.
Lemma YBBY_yel_odd n i : n./2.+1 <= i -> odd i -> coloringYBBY n i = yel.
Proof. by move=> r oi; rewrite /coloringYBBY oi !(andbF,andbT) leqNgt orbF r. Qed.
Lemma YBBY_blu_odd n i : i <= n./2 -> odd i -> coloringYBBY n i = blu.
Proof. by move=> ni oi; rewrite /coloringYBBY ni oi. Qed.
Lemma YBBY_blu_even n i : n./2.+1 <= i <= n -> ~~ odd i -> coloringYBBY n i = blu.
Proof. by move=> ni /negbTE oi; rewrite /coloringYBBY oi !(andbT,andbF) ni. Qed.
Lemma YBBY_both n : odd n -> coloringYBBY n 0 = coloringYBBY n n.
Proof.
  move=> on; rewrite /coloringYBBY leq0n on/= !(andbF,andbT) orbF.
  rewrite ifF //; apply/negbTE; rewrite -ltnNge.
  by rewrite -{2}(odd_double_half n) on add1n ltnS -addnn leq_addl.
Qed.

Section TCTP_nec_shortodd.
Variables (colfun : coloring) (k n : nat).
Hypotheses (n_range : 3 ^ k < n <= (3 ^ k).*2) (on : odd n).
Hypothesis H : CFun colfun.
Hypothesis vertices : forall x y, WellColoredVertices colfun x y (3 ^ k).
Hypothesis topcolor : forall i, i <= n -> coloringYBBY n i = colfun i 0.

Let shortodd_coloringYB i : i <= n - 3 ^ k -> coloringYB (n - 3 ^ k) i = colfun i (3 ^ k).
Proof.
  move=> i_range.
  have i_range' : i + 3 ^ k <= n by rewrite addnC -leq_subRL// ltnW//; move/andP : n_range => [].
  have i_leq_n : i <= n by rewrite (leq_trans i_range)// leq_subr.
  have n_range_lt : n < (3 ^ k).*2.
  move: n_range => /andP[_]; rewrite leq_eqVlt => /predU1P[n_range_eq|//].
  by move: on; rewrite n_range_eq odd_double.
  have hn_range_lt : n./2 < 3 ^ k.
  rewrite -(@ltn_pmul2l 2)// !mul2n (leq_trans _ n_range_lt)// ltnS.
  by rewrite -{2}(odd_double_half n) on add1n.
  have hn_range_lt' : n./2 < i + 3 ^ k by rewrite ltn_addl //.
  have hn_geq_i : i <= n./2. apply: (leq_trans i_range).
  by rewrite leq_subCl -{1}(odd_double_half n) on add1n -addnn subSn ?leq_addr// -addnBA// subnn addn0.
  have -> : colfun i (3 ^ k) = mix (colfun i 0) (colfun (i + 3 ^ k) 0) by rewrite -vertices.
  have <- : coloringYBBY n i = colfun i 0 by exact /topcolor /i_leq_n.
  have <- : coloringYBBY n (i + 3 ^ k) = colfun (i + 3 ^ k) 0 by rewrite topcolor.
  have [oi|ei] := boolP (odd i).
  - have -> : coloringYBBY n i = blu by exact: YBBY_blu_odd.
    have -> : coloringYBBY n (i + 3 ^ k) = blu.
    by rewrite YBBY_blu_even// ?hn_range_lt'// oddD oddX orbT oi.
    have ->// : coloringYB (n - 3 ^ k) i = blu by rewrite /coloringYB oi i_range //.
  - have -> : coloringYBBY n i = yel by exact: YBBY_yel_even.
    have -> : coloringYBBY n (i + 3 ^ k) = yel.
    by rewrite YBBY_yel_odd// ?hn_range_lt'// oddD oddX orbT /= addbT ei.
    have ->// : coloringYB (n - 3 ^ k) i = yel by rewrite /coloringYB ei i_range //.
Qed.

Lemma shortodd_bottom : colfun 0 n = red.
Proof.
  have shortodd_coloringYB_next_red i : i <= (n - 3 ^ k).-1 -> colfun i (3 ^ k).+1 = red.
  have n_gt_0: 0 < n - 3 ^ k by rewrite ltn_subCr subn0; move /andP : n_range => [].
  move=> i_range.
  have i_range_leq : i <= n - 3 ^ k by rewrite (leq_trans i_range)// leq_pred.
  have i_range_lt : i.+1 <= n - 3 ^ k by rewrite (leq_ltn_trans i_range)// ltn_predL.
  suff : mix (colfun i (3 ^ k)) (colfun i.+1 (3 ^ k)) = red by move=> <-.
  have [oi|ei] := boolP (odd i).
  - rewrite -shortodd_coloringYB// (_ : coloringYB _ _ = blu).
    by rewrite -shortodd_coloringYB// /coloringYB i_range_lt /= oi.
    by rewrite /coloringYB i_range_leq oi.
  - rewrite -(shortodd_coloringYB i)// (_ : coloringYB _ _ = yel).
    by rewrite -shortodd_coloringYB// /coloringYB i_range_lt /= ei.
    by rewrite /coloringYB ei i_range_leq.
  have -> : n = 3 ^ k + 1 + (n - 3 ^ k).-1.
  have n_gt_0 : 0 < n - 3^k by rewrite ltn_subCr subn0; case /andP : n_range.
  by rewrite -addnA addnC add1n prednK// ?subnK// ?subn_gt0// ltnW// -subn_gt0.
  by rewrite allred// => i ?; rewrite addn1 shortodd_coloringYB_next_red.
Qed.
End TCTP_nec_shortodd.

Lemma TCTP_nec_shortodd n k : 3 ^ k < n <= (3 ^ k).*2 -> odd n -> ~ WellColoredTriangle 0 0 n.
Proof.
  move=> n_range on WCT.
  have [colfun [H lift]] : exists colfun, CFun colfun /\ forall x y, colfun x y = liftcoloring (fun z => coloringYBBY n z) x y
  by exists (liftcoloring (fun z => coloringYBBY n z)).
  have := WCT colfun H; rewrite /WellColoredVertices addnC addn0.
  have topcolor i : coloringYBBY n i = colfun i 0 by rewrite lift //=.
  have <- : colfun 0 0 = colfun n 0; first by rewrite lift -topcolor -YBBY_both//= subnn.
  have -> : colfun 0 0 = yel by rewrite lift//=.
  have -> // : colfun 0 n = red.
  apply: (shortodd_bottom _ k) => // ? ?; exact: TCTP_suf.
Qed.
(* End: TCTP_nec_shortodd --------------------*)

(* Begin: TCTP_nec_longodd --------------------*)
(* colorBYB x n k z : paint the topmost cells from x to x+n
   - blue for the left-most 3^k cells + the right-most 3^k cells
   - yellow for other cells
  (- blue for cells out of the range)
*)
Definition coloringBYB n k i := if 3 ^ k <= i <= n - 3 ^ k then yel else blu.

(* Some properties of colorBYB *)
Lemma BYB_blu_left n k i : i <= (3 ^ k).-1 -> coloringBYB n k i = blu.
Proof.
  move=> range; rewrite /coloringBYB ifF//; apply/negbTE.
  by rewrite negb_and -ltnNge (leq_ltn_trans range)//= prednK// expn_gt0.
Qed.
Lemma BYB_yel_center n k i : 3 ^ k <= i <= n - 3 ^ k -> coloringBYB n k i = yel.
Proof. by move=> range; rewrite /coloringBYB range. Qed.
Lemma BYB_blu_right n k i : (n - 3 ^ k).+1 <= i -> coloringBYB n k i = blu.
Proof. by move=> range; rewrite /coloringBYB ifF//; apply/negbTE;rewrite negb_and orbC -ltnNge range. Qed.

Section TCTP_nec_longodd.
Variables (colfun : coloring) (k n : nat).
Hypotheses (n_range : (3 ^ k).*2.+1 <= n < 3 ^ k.+1) (H : CFun colfun).
Hypothesis vertices : forall x y, WellColoredVertices colfun x y (3 ^ k).
Hypothesis topcolor : forall i, i <= n -> coloringBYB n k i = colfun i 0.

(* An inequality obtained from the range of n *)
Let inequality : prod (3 ^ k <= n) (prod ((3 ^ k).*2 <= n) (n - (3 ^ k).*2 <= (3 ^ k).-1)).
Proof.
  move: n_range => /andP[n_range_left n_range_right]; split.
  - by rewrite (leq_trans _ n_range_left)// -addnn -addnS leq_addr.
  - rewrite (ltnW n_range_left); split => [//|].
    rewrite leq_subLR -addnn -ltnS -addnS prednK// ?expn_gt0//.
    move: n_range_right; rewrite expnSr; move/leq_trans; apply.
    by rewrite {2}(_ : 3 = 1 + 1 + 1)// 2!mulnDr !muln1.
Qed.

Let longodd_red_both_sides :
  (forall i, i <= n - (3 ^ k).*2 -> colfun i (3 ^ k) = red) /\
  (forall i, 3 ^ k <= i <= n - 3 ^ k -> colfun i (3 ^ k) = red).
Proof.
  split=> [i i_range_right|i /andP[i_range_left i_range_right]];
  have i_leq_n : i <= n by rewrite (leq_trans i_range_right)// leq_subr.
  - have i_range_right' : 3 ^ k + i <= n - 3 ^ k.
    by rewrite leq_subRL// ?inequality// addnA addnn -leq_subRL// inequality.
    have n_range_geq : 3 ^ k + i <= n by rewrite (leq_trans i_range_right')// leq_subr.
    have -> := vertices i 0; rewrite /WellColoredVertices.
    have -> : colfun i 0 = blu.
    rewrite -topcolor//; apply: BYB_blu_left => //.
    by rewrite (leq_trans i_range_right) // inequality.
    have ->// : colfun (i + (3 ^ k)) 0 = yel.
    by rewrite -topcolor// (addnC i) // BYB_yel_center// leq_addr i_range_right'//.
  - have ni_range : n - 3 ^ k < 3 ^ k + i.
    rewrite ltn_subLR// ?(leq_trans i_range_left)// addnA addnn.
    case /andP: n_range => _ /leq_trans ->//.
    by rewrite expnS (mulnDl 1 2) addnC mul2n mul1n leq_add2l.
    have -> := vertices i 0; rewrite /WellColoredVertices.
    have -> : colfun i 0 = yel
    by rewrite -topcolor // ?(BYB_yel_center n k i)// i_range_left i_range_right.
    have ->// : colfun (i + 3 ^ k) 0 = blu; rewrite -topcolor// addnC; first by apply BYB_blu_right.
    by rewrite -leq_subRL// inequality.
Qed.

Lemma longodd_bottom : colfun 0 n = red.
Proof.
  have longodd_redline i : i <= n - (3 ^ k).*2 -> colfun i (3 ^ k).*2 = red.
  move=> i_range; rewrite -addnn.
  have in_range : i + 3 ^ k <= n - 3 ^ k.
  by rewrite leq_subRL// ?inequality// addnCA addnn addnC -leq_subRL// inequality.
  have ->// := vertices i (3 ^ k); rewrite /WellColoredVertices.
  have ->// : colfun i (3 ^ k) = red by exact: longodd_red_both_sides.1.
  have ->// : colfun (i + 3 ^ k) (3 ^ k) = red.
  by apply: longodd_red_both_sides.2; rewrite leq_addl.
  have // : colfun 0 ((3^k).*2 + (n - (3^k).*2)) = red by rewrite allred//.
  by rewrite addnC subnK// inequality.
Qed.
End TCTP_nec_longodd.

Lemma TCTP_nec_longodd n k :
  (3 ^ k).*2.+1 <= n < 3 ^ k.+1 -> ~ WellColoredTriangle 0 0 n.
Proof.
  move=> n_range WCT.
  have [colfun [H lift]] : exists colfun, CFun colfun /\ forall x y, colfun x y = liftcoloring (fun z => coloringBYB n k z) x y
  by exists (liftcoloring (fun z => coloringBYB n k z)).
  have := WCT colfun H; rewrite /WellColoredVertices addnC addn0.
  have topcolor i : i <= n -> coloringBYB n k i = colfun i 0; first by rewrite lift /=.
  rewrite /WellColoredTriangle in WCT.
  have triangle x y : WellColoredVertices colfun x y (3 ^ k); first exact: TCTP_suf.
  have -> : colfun 0 n = red; first by exact: (longodd_bottom _ k).
  have -> : colfun 0 0 = blu by rewrite -(addn0 0) -topcolor// BYB_blu_left.
  have ->// : colfun n 0 = blu.
  rewrite -topcolor// BYB_blu_right// -ltn_subCl// ?subnn ?expn_gt0//.
  by move /andP : n_range => [+ _]; apply: leq_trans; rewrite leqW// -addnn leq_addl.
Qed.
(* End: TCTP_nec_longodd --------------------*)

Lemma nat_case n : exists k, n = 0 \/ n = 3 ^ k \/ 3 ^ k < n <= (3 ^ k).*2 \/ (3 ^ k).*2.+1 <= n < 3 ^ k.+1.
Proof.
  elim: n => [|n [k [IH0|[IH1|[|]]]]]; first by exists 0; left.
  - exists 0; right; left; by rewrite IH0.
  - exists k; right; right; left; by rewrite -IH1 -addnn -addn1 !leq_add2l IH1 expn_gt0.
  - case /andP => IH2L; rewrite leq_eqVlt => /predU1P[->|IH2R].
    case: k IH2L => [|k]; first by exists 1 ; right; left; rewrite expn0 expn1.
    exists (k.+1); right; right; right; apply /andP; split; first by[].
    rewrite (expnSr 3 k.+1) {3}(_:3 = 2+1)// -(addn1 ((3^k.+1).*2)) mulnDr muln2 ltn_add2l muln1.
    by rewrite expnS (ltn_trans (ltnSn 1))// -{1}(muln1 3) leq_pmul2l//expn_gt0.
    by exists k; right; right; left; apply/andP; split; [exact:ltnW|].
  - case /andP => IH3L; rewrite leq_eqVlt => /predU1P[|IH3R]; first by exists (k.+1); right; left.
    by exists k; right; right; right; apply/andP; split; [rewrite (ltn_trans IH3L)|].
Qed.

Theorem TCTP_nec n :
  n > 0 -> WellColoredTriangle 0 0 n -> exists k, n = 3 ^ k.
Proof.
  move=> + WCT; case: (nat_case n) => k [->//|n_case n_gt0].
  have [on|en] := boolP (odd n).
  - case: n_case => [n_is_exp3k|[shortodd|longodd]]; first by exists k.
    + by exfalso; exact: (TCTP_nec_shortodd n k).
    + by exfalso; exact: (TCTP_nec_longodd n k).
  - by exfalso; exact: (TCTP_nec_even n).
Qed.

(* Main Theorem *)
Theorem TCTP n :
  n > 0 -> (exists k, n = 3 ^ k) <-> WellColoredTriangle 0 0 n.
Proof.
  move=> n_gt0; split => [[k] n_is_exp3k|]; first rewrite n_is_exp3k.
  - exact: TCTP_suf k 0 0.
  - exact: TCTP_nec.
Qed.

End TCTP.


(* Exercise coq_nat_04 *)

(* Let us prove that addition is commutative. *)

(* For this we may need the facts that '0' is a neutral element for
   addition and that 'S (n + m) = n + S m' - the facts that we proved
   before. However, those results are also available in the standard
   library. First we need to make them available with the
   'Require Import' command. *)

Require Import Plus.
Check Nat.add_0_l.
Check Nat.add_0_r.
Check plus_n_Sm.

Lemma plus_comm : forall m n, m + n = n + m.

Proof.
intros.
induction m.
simpl.
rewrite Nat.add_0_r.
reflexivity.
(*step*)
simpl.
rewrite -> IHm.
rewrite plus_n_Sm.
reflexivity.

Qed.


(**---
content_type: md
layout: main
header_style: max-height:50px;
click: download('/')
title: "Konstantin Weitz: (Dis)advantages of using Abstract Data Types in Proof Assistants"
comments: true
info:
---

(Dis)advantages of using Abstract Data Types in Proof Assistants
----------------------------------------------------------------

This blog post explains the advantages and disadvantages of using
Abstract Data Types (ADTs, see TaPL Chapter 24) in a Proof Assistant.
On the plus side, ADTs promote data representation independence, code reuse,
and clean code extraction; but they also do not support fix/match syntax,
have to expose derived operations, and prohibit computational reasoning.

<!--more-->

Download this blog post's code [here][dl].

[dl]: /assets/posts/coq-adts/CoqADT.v

### Represenation Independence

Consider Coq's standard library implementation of natural number addition `add`:
**)

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

(**
This implementation is unsatisfactory, as it exposes the data representation details of the
`nat` datatype. For example, this implementation of `add` will not work with a more
space efficient binary representation of natural numbers.

The standard solution to this problem is to **hide the data representation using an ADT**. ADTs can be
implemented using either Modules ([see][mod]), Sigma/Existential Types (see TaPL Chapter 24),
Records ([see][agda]), or Type Classes ([see][tc]).
In this blog post, we choose to implement ADTs in the Coq Proof
Assistants using Type Classes.

Our ADT for natural numbers `NatADT` consists of:
a type `Nat` whose representation is hidden,
operations on the type (`zero`, `succ`, `natRect`), and
equations that describe the operation's behavior (`natRectZero`, `natRectSucc`).

The operation `natRect` is the [eliminator for natural numbers][cmb].
The equations describe the computational behavior of `natRect`.

[tc]: http://www.labri.fr/perso/casteran/CoqArt/TypeClassesTut/typeclassestut.pdf
[agda]: https://stackoverflow.com/questions/26888499/how-to-define-abstract-types-in-agda
[mod]: http://www.cs.princeton.edu/~appel/vfa/ADT.html
[cmb]: https://www.quora.com/In-type-theory-what-is-an-eliminator-and-what-is-its-opposite
**)

    Class NatADT := {
      Nat : Type;
      zero : Nat;
      succ : Nat -> Nat;
      natRect : forall P, P zero -> (forall n, P n -> P (succ n)) -> forall n, P n;
      natRectZero : forall P z s, natRect P z s zero = z;
      natRectSucc : forall P z s n, natRect P z s (succ n) = s n (natRect P z s n)
    }.

(**
Given this ADT, we can now implement an `add` function that is **independent
of any particular implementation** of the natural numbers (hurray).

Unfortunately, this also means that we have to implement the code in
terms of the eliminator, and **cannot use fix/match syntax**
(sigh). However, getting around this syntactic restriction would be trivial
for eliminator based languages like Lean.
**)

    Definition add `{NatADT} (n m:Nat) : Nat :=
      natRect _ m (fun _ rec => succ rec) n.

(**

### Code Reuse

We can instantiate the ADT using Coq's standard library
natural numbers, ...
**)

    Instance natNat : NatADT := {|
      Nat := nat;
      zero := 0;
      succ := S;
      natRect := nat_rect
    |}.
    Proof.
      - reflexivity.
      - reflexivity.
    Defined.

(**
... and call the `add` function as we please.
**)

    Compute (@add natNat 5 7).

(**
We can even prove that our implementation of `add` is
equivalent to the standard library operation `Nat.add` (`+`).
**)

    Lemma eqAddAdd (n m : nat) : n + m = add n m.
      induction n; cbn in *; congruence.
    Qed.

(**
We can also instantiate the ADT using Coq's binary natural numbers `N`, ...
**)

    Require Import NArith.

    Open Scope N.

    Instance NNat : NatADT := {|
      Nat := N;
      zero := N.zero;
      succ := N.succ;
      natRect := N.peano_rect
    |}.
    Proof.
      - apply N.peano_rect_base.
      - apply N.peano_rect_succ.
    Defined.

(**
... and call the `add` function as we please.
**)

    Compute (@add NNat 5 7).

(**

ADTs thus **enable code reuse**, because a function has to only be implemented
once for an ADT, instead of every single instatiation of the ADT.

While this instantiation of `add` is exponentially more space efficient
than the instantiation with `natNat`, the computation still requires
time exponential in the number of `n`'s bits.

The problem of ADTs is that they hide implementation details, and thus
deny opportunities for optimization.
To overcome this problem, ADT implementers have to guess and **expose all the operations
that some future instatiation of the ADT can implement more efficiently**
(even if they can be implemented
less efficiently using other operations of the ADT). The result is an ADT that
is hard to understand (because the essential operations are swamped by derived operations)
and inefficient (because some optimization opportunity will inevitably be lost for lack of precognition).
**)

(**

### Extracting ADTs

**ADTs are also useful for extraction**. We can instantiate an ADT using opaque terms
that will be implemented on extraction.
**)

    Parameter HsNat : Type.
    Parameter hsZero : HsNat.
    Parameter hsSucc : HsNat -> HsNat.
    Parameter hsNatRect : forall P, P hsZero -> (forall n, P n -> P (hsSucc n)) -> forall n, P n.
    Axiom hsNatRectZero : forall P z s, hsNatRect P z s hsZero = z.
    Axiom hsNatRectSucc : forall P z s n, hsNatRect P z s (hsSucc n) = s n (hsNatRect P z s n).

    Extraction Language Haskell.

    Extract Constant HsNat => "Prelude.Integer".
    Extract Constant hsZero => "0".
    Extract Constant hsSucc => "Prelude.succ".
    Extract Constant hsNatRect => "(\z s -> let f n = if n Prelude.== 0
                                                     then z
                                                     else s (Prelude.pred n)
                                                            (f (Prelude.pred n)) in f)".

    Instance HsNatNat : NatADT := {|
                                   Nat := HsNat;
                                   zero := hsZero;
                                   succ := hsSucc;
                                   natRect := hsNatRect
                                 |}.
    Proof.
      - apply hsNatRectZero.
      - apply hsNatRectSucc.
    Defined.

    Definition hsAdd : HsNat := @add HsNatNat (hsSucc (hsSucc hsZero)) (hsSucc hsZero).
    Extraction "src/Add.hs" hsAdd.

(**
This approach clearly documents all the terms that have to be implemented
by extraction (`Parameter`) and the assumptions about their behavior
(`Axiom`), and is thus cleaner than the common alternative of
syntactically replacing arbitrary Coq terms and data types:
**)

    Extract Inductive nat => "Prelude.Integer" ["0" "Prelude.succ"]
                                            "(\z s n -> if n Prelude.== 0
                                                        then z ()
                                                        else s (Prelude.pred n))".

    Definition hsAddNat : nat := 2 + 1.
    Extraction "src/AddNat.hs" hsAddNat.

(**

### Reasoning About ADTs

There is another major downside to using ADTs — they severely impact
theorem proving. Consider the following proof that `0 + n = n + 0` using
Coq's standard library natural numbers. After the induction, the proof
is almost automatic due to Coq's ability to computationally simplify (`cbn`)
the goal.
**)

    Open Scope nat.

    Lemma natAddZero (n : nat) : 0 + n = n + 0.
      induction n as [|n' IHn'].
      - reflexivity.
      - cbn in IHn'.         (* A *)
        rewrite IHn' at 1.   (* B *)
        cbn.                 (* C *)
        reflexivity.
    Qed.

(**
Compare this to the proof which uses the ADT, where we have to
**perform equational reasoning instead of computational reasoning**.
This is extremely burdensome, especially for more complicated proofs.
**)

    Lemma addZero `{Nat} n : add zero n = add n zero.
      refine (natRect (fun n => add zero n = add n zero) _ (fun n' IHn' => _) n).
      - reflexivity.
      - unfold add in IHn'.             (* A *)
        rewrite natRectZero in IHn'.    (* A *)
        rewrite IHn' at 1.              (* B *)
        unfold add.                     (* C *)
        rewrite natRectSucc.            (* C *)
        rewrite natRectZero.            (* C *)
        reflexivity.
    Qed.

(**

### Summary

In summary, there are several advantages to using ADTs:

- ADTs are data representation independent.
- ADTs enable code reuse.
- ADTs enable clean extraction.

But there are also drawbacks:

- ADTs do not support fix/match syntax.
- ADTs have to expose derived operations.
- ADTs prohibit computational reasoning.

**)


(** * Prop: Propositions and Evidence *)

Require Export Logic.

(* ####################################################### *)
(** ** From Boolean Functions to Propositions *)

(** In chapter [Basics] we defined a _function_ [evenb] that tests a
    number for evenness, yielding [true] if so.  We can use this
    function to define the _proposition_ that some number [n] is
    even: *)

Definition even (n:nat) : Prop :=
  evenb n = true.

(** That is, we can define "[n] is even" to mean "the function [evenb]
    returns [true] when applied to [n]."

    Note that here we have given a name
    to a proposition using a [Definition], just as we have
    given names to expressions of other sorts. This isn't a fundamentally
    new kind of proposition;  it is still just an equality. *)

(** Another alternative is to define the concept of evenness
    directly.  Instead of going via the [evenb] function ("a number is
    even if a certain computation yields [true]"), we can say what the
    concept of evenness means by giving two different ways of
    presenting _evidence_ that a number is even. *)

(** ** Inductively Defined Propositions *)

Inductive ev : nat -> Prop :=
  | ev_0 : ev O
  | ev_SS : forall n:nat, ev n -> ev (S (S n)).

(** This definition says that there are two ways to give
    evidence that a number [m] is even.  First, [0] is even, and
    [ev_0] is evidence for this.  Second, if [m = S (S n)] for some
    [n] and we can give evidence [e] that [n] is even, then [m] is
    also even, and [ev_SS n e] is the evidence. *)

(** **** Exercise: 1 star (double_even) *)

Theorem double_even : forall n,
  ev (double n).
Proof.
  intros.
  induction n as [|n'].
  simpl. apply ev_0.
  simpl. apply ev_SS. apply IHn'.
Qed.

(** *** Discussion: Computational vs. Inductive Definitions *)

(** We have seen that the proposition "[n] is even" can be
    phrased in two different ways -- indirectly, via a boolean testing
    function [evenb], or directly, by inductively describing what
    constitutes evidence for evenness.  These two ways of defining
    evenness are about equally easy to state and work with.  Which we
    choose is basically a question of taste.

    However, for many other properties of interest, the direct
    inductive definition is preferable, since writing a testing
    function may be awkward or even impossible.

    One such property is [beautiful].  This is a perfectly sensible
    definition of a set of numbers, but we cannot translate its
    definition directly into a Coq Fixpoint (or into a recursive
    function in any other common programming language).  We might be
    able to find a clever way of testing this property using a
    [Fixpoint] (indeed, it is not too hard to find one in this case),
    but in general this could require arbitrarily deep thinking.  In
    fact, if the property we are interested in is uncomputable, then
    we cannot define it as a [Fixpoint] no matter how hard we try,
    because Coq requires that all [Fixpoint]s correspond to
    terminating computations.

    On the other hand, writing an inductive definition of what it
    means to give evidence for the property [beautiful] is
    straightforward. *)

(** **** Exercise: 1 star (ev__even) *)
(** Here is a proof that the inductive definition of evenness implies
    the computational one. *)

Theorem ev__even : forall n,
  ev n -> even n.
Proof.
  intros n E.
 induction E as [| n' E'].
  Case "E = ev_0".
    unfold even. reflexivity.
  Case "E = ev_SS n' E'".
    unfold even. apply IHE'.
Qed.

(** Could this proof also be carried out by induction on [n] instead
    of [E]?  If not, why not? *)

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

(** The induction principle for inductively defined propositions does
    not follow quite the same form as that of inductively defined
    sets.  For now, you can take the intuitive view that induction on
    evidence [ev n] is similar to induction on [n], but restricts our
    attention to only those numbers for which evidence [ev n] could be
    generated.  We'll look at the induction principle of [ev] in more
    depth below, to explain what's really going on. *)

(** **** Exercise: 1 star (l_fails) *)
(** The following proof attempt will not succeed.
     Theorem l : forall n,
       ev n.
     Proof.
       intros n. induction n.
         Case "O". simpl. apply ev_0.
         Case "S".
           ...
   Intuitively, we expect the proof to fail because not every
   number is even. However, what exactly causes the proof to fail?

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

(** **** Exercise: 2 stars (ev_sum) *)
(** Here's another exercise requiring induction. *)

Theorem ev_sum : forall n m,
   ev n -> ev m -> ev (n+m).
Proof.
  intros.
  induction H as [|n' H'].
  simpl.  apply H0.
  simpl. apply ev_SS.  apply IHH'.
Qed.
(** [] *)

(* ##################################################### *)
(** * Inductively Defined Propositions *)

(**  As a running example, let's
    define a simple property of natural numbers -- we'll call it
    "[beautiful]." *)

(** Informally, a number is [beautiful] if it is [0], [3], [5], or the
    sum of two [beautiful] numbers.

    More pedantically, we can define [beautiful] numbers by giving four
    rules:

       - Rule [b_0]: The number [0] is [beautiful].
       - Rule [b_3]: The number [3] is [beautiful].
       - Rule [b_5]: The number [5] is [beautiful].
       - Rule [b_sum]: If [n] and [m] are both [beautiful], then so is
         their sum. *)
(** ** Inference Rules *)
(** We will see many definitions like this one during the rest
    of the course, and for purposes of informal discussions, it is
    helpful to have a lightweight notation that makes them easy to
    read and write.  _Inference rules_ are one such notation: *)
(**
                              -----------                               (b_0)
                              beautiful 0

                              ------------                              (b_3)
                              beautiful 3

                              ------------                              (b_5)
                              beautiful 5

                       beautiful n     beautiful m
                       ---------------------------                      (b_sum)
                              beautiful (n+m)
*)

(** *** *)
(** Each of the textual rules above is reformatted here as an
    inference rule; the intended reading is that, if the _premises_
    above the line all hold, then the _conclusion_ below the line
    follows.  For example, the rule [b_sum] says that, if [n] and [m]
    are both [beautiful] numbers, then it follows that [n+m] is
    [beautiful] too.  If a rule has no premises above the line, then
    its conclusion holds unconditionally.

    These rules _define_ the property [beautiful].  That is, if we
    want to convince someone that some particular number is [beautiful],
    our argument must be based on these rules.  For a simple example,
    suppose we claim that the number [5] is [beautiful].  To support
    this claim, we just need to point out that rule [b_5] says so.
    Or, if we want to claim that [8] is [beautiful], we can support our
    claim by first observing that [3] and [5] are both [beautiful] (by
    rules [b_3] and [b_5]) and then pointing out that their sum, [8],
    is therefore [beautiful] by rule [b_sum].  This argument can be
    expressed graphically with the following _proof tree_: *)
(**
         ----------- (b_3)   ----------- (b_5)
         beautiful 3         beautiful 5
         ------------------------------- (b_sum)
                   beautiful 8
*)
(** *** *)
(**
    Of course, there are other ways of using these rules to argue that
    [8] is [beautiful], for instance:
         ----------- (b_5)   ----------- (b_3)
         beautiful 5         beautiful 3
         ------------------------------- (b_sum)
                   beautiful 8
*)

(** **** Exercise: 1 star (varieties_of_beauty) *)
(** How many different ways are there to show that [8] is [beautiful]? *)

(* 2 ways *)
(** [] *)

(** *** *)
(** In Coq, we can express the definition of [beautiful] as
    follows: *)

Inductive beautiful : nat -> Prop :=
  b_0   : beautiful 0
| b_3   : beautiful 3
| b_5   : beautiful 5
| b_sum : forall n m, beautiful n -> beautiful m -> beautiful (n+m).

(** The first line declares that [beautiful] is a proposition -- or,
    more formally, a family of propositions "indexed by" natural
    numbers.  (That is, for each number [n], the claim that "[n] is
    [beautiful]" is a proposition.)  Such a family of propositions is
    often called a _property_ of numbers.  Each of the remaining lines
    embodies one of the rules for [beautiful] numbers.
*)
(** *** *)
(**
    The rules introduced this way have the same status as proven
    theorems; that is, they are true axiomatically.
    So we can use Coq's [apply] tactic with the rule names to prove
    that particular numbers are [beautiful].  *)

Theorem three_is_beautiful: beautiful 3.
Proof.
   (* This simply follows from the rule [b_3]. *)
   apply b_3.
Qed.

Theorem eight_is_beautiful: beautiful 8.
Proof.
   (* First we use the rule [b_sum], telling Coq how to
      instantiate [n] and [m]. *)
   apply b_sum with (n:=3) (m:=5).
   (* To solve the subgoals generated by [b_sum], we must provide
      evidence of [beautiful 3] and [beautiful 5]. Fortunately we
      have rules for both. *)
   apply b_3.
   apply b_5.
Qed.

(** *** *)
(** As you would expect, we can also prove theorems that have
hypotheses about [beautiful]. *)

Theorem beautiful_plus_eight: forall n, beautiful n -> beautiful (8+n).
Proof.
  intros n B.
  apply b_sum with (n:=8) (m:=n).
  apply eight_is_beautiful.
  apply B.
Qed.

(** **** Exercise: 2 stars (b_times2) *)
Theorem b_times2: forall n, beautiful n -> beautiful (2*n).
Proof.
  intros.
  simpl.
  apply b_sum.
  apply H.
  rewrite -> plus_0_r.
  apply H.
Qed.
(** [] *)

(** **** Exercise: 3 stars (b_timesm) *)
Theorem b_timesm: forall n m, beautiful n -> beautiful (m*n).
Proof.
   intros.
   induction m as [|m'].
   simpl. apply b_0.
   apply b_sum.  apply H.
   apply IHm'.
Qed.
(** [] *)

(* ####################################################### *)
(** ** Induction Over Evidence *)

(** Besides _constructing_ evidence that numbers are beautiful, we can
    also _reason about_ such evidence. *)

(** The fact that we introduced [beautiful] with an [Inductive]
    declaration tells Coq not only that the constructors [b_0], [b_3],
    [b_5] and [b_sum] are ways to build evidence, but also that these
    four constructors are the _only_ ways to build evidence that
    numbers are beautiful. *)

(** In other words, if someone gives us evidence [E] for the assertion
    [beautiful n], then we know that [E] must have one of four shapes:

      - [E] is [b_0] (and [n] is [O]),
      - [E] is [b_3] (and [n] is [3]),
      - [E] is [b_5] (and [n] is [5]), or
      - [E] is [b_sum n1 n2 E1 E2] (and [n] is [n1+n2], where [E1] is
        evidence that [n1] is beautiful and [E2] is evidence that [n2]
        is beautiful). *)

(** *** *)
(** This permits us to _analyze_ any hypothesis of the form [beautiful
    n] to see how it was constructed, using the tactics we already
    know.  In particular, we can use the [induction] tactic that we
    have already seen for reasoning about inductively defined _data_
    to reason about inductively defined _evidence_.

    To illustrate this, let's define another property of numbers: *)

Inductive gorgeous : nat -> Prop :=
  g_0 : gorgeous 0
| g_plus3 : forall n, gorgeous n -> gorgeous (3+n)
| g_plus5 : forall n, gorgeous n -> gorgeous (5+n).

(** **** Exercise: 1 star (gorgeous_tree) *)
(** Write out the definition of [gorgeous] numbers using inference rule
    notation.

(* FILL IN HERE *)
        -------------- g_0
            gorgeous 0

           gorgeous n
        -------------- g_plus3
           gorgeous (3+n)

          gorgeous n
        -------------- g_plus5
          gorgeous(5+n)
*)

(** **** Exercise: 1 star (gorgeous_plus13) *)
Theorem gorgeous_plus13: forall n,
  gorgeous n -> gorgeous (13+n).
Proof.
  intros.
  simpl. apply g_plus5. apply g_plus5. apply g_plus3. apply H.
Qed.
(** [] *)

(** *** *)
(** It seems intuitively obvious that, although [gorgeous] and
    [beautiful] are presented using slightly different rules, they are
    actually the same property in the sense that they are true of the
    same numbers.  Indeed, we can prove this. *)

Theorem gorgeous__beautiful : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros n H.
   induction H as [|n'|n'].
   Case "g_0".
       apply b_0.
   Case "g_plus3".
       apply b_sum. apply b_3.
       apply IHgorgeous.
   Case "g_plus5".
       apply b_sum. apply b_5. apply IHgorgeous.
Qed.

(** Notice that the argument proceeds by induction on the _evidence_ [H]! *)

(** Let's see what happens if we try to prove this by induction on [n]
   instead of induction on the evidence [H]. *)

Theorem gorgeous__beautiful_FAILED : forall n,
  gorgeous n -> beautiful n.
Proof.
   intros. induction n as [| n'].
   Case "n = 0". apply b_0.
   Case "n = S n'". (* We are stuck! *)
Abort.

(** The problem here is that doing induction on [n] doesn't yield a
    useful induction hypothesis. Knowing how the property we are
    interested in behaves on the predecessor of [n] doesn't help us
    prove that it holds for [n]. Instead, we would like to be able to
    have induction hypotheses that mention other numbers, such as [n -
    3] and [n - 5]. This is given precisely by the shape of the
    constructors for [gorgeous]. *)

(** **** Exercise: 2 stars (gorgeous_sum) *)
Theorem gorgeous_sum : forall n m,
  gorgeous n -> gorgeous m -> gorgeous (n + m).
Proof.
  intros.
  induction H as [|n'|n'].
  simpl. apply H0. apply g_plus3.  apply IHgorgeous.
  apply g_plus5. apply IHgorgeous.
Qed.

(** [] *)

(** **** Exercise: 3 stars, advanced (beautiful__gorgeous) *)
Theorem beautiful__gorgeous : forall n, beautiful n -> gorgeous n.
Proof.
  intros.
  induction H.

Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (g_times2) *)
(** Prove the [g_times2] theorem below without using [gorgeous__beautiful].
    You might find the following helper lemma useful. *)

Lemma helper_g_times2 : forall x y z, x + (z + y)= z + x + y.
Proof.
   (* FILL IN HERE *) Admitted.

Theorem g_times2: forall n, gorgeous n -> gorgeous (2*n).
Proof.
   intros n H. simpl.
   induction H.
   (* FILL IN HERE *) Admitted.
(** [] *)

(* ####################################################### *)
(** ** [Inversion] on Evidence *)

(** Another situation where we want to analyze evidence for evenness
    is when proving that, if [n] is even, then [pred (pred n)] is
    too.  In this case, we don't need to do an inductive proof.  The
    right tactic turns out to be [inversion].  *)

Theorem ev_minus2: forall n,
  ev n -> ev (pred (pred n)).
Proof.
  intros n E.
  inversion E as [| n' E'].
  Case "E = ev_0". simpl. apply ev_0.
  Case "E = ev_SS n' E'". simpl. apply E'.  Qed.

(** **** Exercise: 1 star, optional (ev_minus2_n) *)
(** What happens if we try to use [destruct] on [n] instead of [inversion] on [E]? *)

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

(** *** *)
(** Another example, in which [inversion] helps narrow down to
the relevant cases. *)

Theorem SSev__even : forall n,
  ev (S (S n)) -> ev n.
Proof.
  intros n E.
  inversion E as [| n' E'].
  apply E'. Qed.

(** ** [inversion] revisited *)

(** These uses of [inversion] may seem a bit mysterious at first.
    Until now, we've only used [inversion] on equality
    propositions, to utilize injectivity of constructors or to
    discriminate between different constructors.  But we see here
    that [inversion] can also be applied to analyzing evidence
    for inductively defined propositions.

    (You might also expect that [destruct] would be a more suitable
    tactic to use here. Indeed, it is possible to use [destruct], but
    it often throws away useful information, and the [eqn:] qualifier
    doesn't help much in this case.)

    Here's how [inversion] works in general.  Suppose the name
    [I] refers to an assumption [P] in the current context, where
    [P] has been defined by an [Inductive] declaration.  Then,
    for each of the constructors of [P], [inversion I] generates
    a subgoal in which [I] has been replaced by the exact,
    specific conditions under which this constructor could have
    been used to prove [P].  Some of these subgoals will be
    self-contradictory; [inversion] throws these away.  The ones
    that are left represent the cases that must be proved to
    establish the original goal.

    In this particular case, the [inversion] analyzed the construction
    [ev (S (S n))], determined that this could only have been
    constructed using [ev_SS], and generated a new subgoal with the
    arguments of that constructor as new hypotheses.  (It also
    produced an auxiliary equality, which happens to be useless here.)
    We'll begin exploring this more general behavior of inversion in
    what follows. *)

(** **** Exercise: 1 star (inversion_practice) *)
Theorem SSSSev__even : forall n,
  ev (S (S (S (S n)))) -> ev n.
Proof.
  intros.
  inversion H as [|n' H'].
  inversion H' as [|n'' H''].
  apply H''.
Qed.

(** The [inversion] tactic can also be used to derive goals by showing
    the absurdity of a hypothesis. *)

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

(** **** Exercise: 3 stars, advanced (ev_ev__ev) *)
(** Finding the appropriate thing to do induction on is a
    bit tricky here: *)

Theorem ev_ev__ev : forall n m,
  ev (n+m) -> ev n -> ev m.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (ev_plus_plus) *)
(** Here's an exercise that just requires applying existing lemmas.  No
    induction or even case analysis is needed, but some of the rewriting
    may be tedious. *)

Theorem ev_plus_plus : forall n m p,
  ev (n+m) -> ev (n+p) -> ev (m+p).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ####################################################### *)
(** * Additional Exercises *)

(** **** Exercise: 4 stars (palindromes) *)
(** A palindrome is a sequence that reads the same backwards as
    forwards.

    - Define an inductive proposition [pal] on [list X] that
      captures what it means to be a palindrome. (Hint: You'll need
      three cases.  Your definition should be based on the structure
      of the list; just having a single constructor
    c : forall l, l = rev l -> pal l
      may seem obvious, but will not work very well.)

    - Prove that
       forall l, pal (l ++ rev l).
    - Prove that
       forall l, pal l -> l = rev l.
*)

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

(** **** Exercise: 5 stars, optional (palindrome_converse) *)
(** Using your definition of [pal] from the previous exercise, prove
    that
     forall l, l = rev l -> pal l.
*)

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

(** **** Exercise: 4 stars, advanced (subsequence) *)
(** A list is a _subsequence_ of another list if all of the elements
    in the first list occur in the same order in the second list,
    possibly with some extra elements in between. For example,
    [1,2,3]
    is a subsequence of each of the lists
    [1,2,3]
    [1,1,1,2,2,3]
    [1,2,7,3]
    [5,6,1,9,9,2,7,3,8]
    but it is _not_ a subsequence of any of the lists
    [1,2]
    [1,3]
    [5,6,2,1,7,3,8]

    - Define an inductive proposition [subseq] on [list nat] that
      captures what it means to be a subsequence. (Hint: You'll need
      three cases.)

    - Prove that subsequence is reflexive, that is, any list is a
      subsequence of itself.

    - Prove that for any lists [l1], [l2], and [l3], if [l1] is a
      subsequence of [l2], then [l1] is also a subsequence of [l2 ++
      l3].

    - (Optional, harder) Prove that subsequence is transitive -- that
      is, if [l1] is a subsequence of [l2] and [l2] is a subsequence
      of [l3], then [l1] is a subsequence of [l3].  Hint: choose your
      induction carefully!
*)

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

(** **** Exercise: 2 stars, optional (R_provability) *)
(** Suppose we give Coq the following definition:
    Inductive R : nat -> list nat -> Prop :=
      | c1 : R 0 []
      | c2 : forall n l, R n l -> R (S n) (n :: l)
      | c3 : forall n l, R (S n) l -> R n l.
    Which of the following propositions are provable?

    - [R 2 [1,0]]
    - [R 1 [1,2,1,0]]
    - [R 6 [3,2,1,0]]
*)

(** [] *)

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

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

Module LeModule.

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

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

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

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

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

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

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

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

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

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

End LeModule.

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

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

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

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

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

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

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

(* FILL IN HERE *)
Inductive total_rel: nat -> nat -> Prop :=
  tot_rel : forall (n m:nat), total_rel n m.

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

Inductive empty_rel: nat -> nat -> Prop :=
  emp_rel : forall (n m:nat), empty_rel 0 0.
(** [] *)

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

Lemma le_trans : forall m n o, m <= n -> n <= o -> m <= o.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem O_le_n : forall n,
  0 <= n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem n_le_m__Sn_le_Sm : forall n m,
  n <= m -> S n <= S m.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem Sn_le_Sm__n_le_m : forall n m,
  S n <= S m -> n <= m.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem le_plus_l : forall a b,
  a <= a + b.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem plus_lt : forall n1 n2 m,
  n1 + n2 < m ->
  n1 < m /\ n2 < m.
Proof.
 unfold lt.
 (* FILL IN HERE *) Admitted.

Theorem lt_S : forall n m,
  n < m ->
  n < S m.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem ble_nat_true : forall n m,
  ble_nat n m = true -> n <= m.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem le_ble_nat : forall n m,
  n <= m ->
  ble_nat n m = true.
Proof.
  (* Hint: This may be easiest to prove by induction on [m]. *)
  (* FILL IN HERE *) Admitted.

Theorem ble_nat_true_trans : forall n m o,
  ble_nat n m = true -> ble_nat m o = true -> ble_nat n o = true.
Proof.
  (* Hint: This theorem can be easily proved without using [induction]. *)
  (* FILL IN HERE *) Admitted.

(** **** Exercise: 2 stars, optional (ble_nat_false) *)
Theorem ble_nat_false : forall n m,
  ble_nat n m = false -> ~(n <= m).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

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

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

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

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

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

(* FILL IN HERE *)
[]
*)

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

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

End R.

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

(** As we have seen, a _proposition_ is a statement expressing a factual claim,
    like "two plus two equals four."  In Coq, propositions are written
    as expressions of type [Prop]. . *)

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

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

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

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

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

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

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

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

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

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

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

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

Theorem plus_fact_is_true :
  plus_fact.
Proof. reflexivity.  Qed.

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

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

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

       - We can combine propositions using implication and
         quantification. *)
(** *** *)
(** We have also seen _parameterized propositions_, such as [even] and
    [beautiful]. *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Definition combine_odd_even (Podd Peven : nat -> Prop) : nat -> Prop :=
  fun n => if evenb n then Peven n else Podd n.

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

Theorem combine_odd_even_intro :
  forall (Podd Peven : nat -> Prop) (n : nat),
    (oddb n = true -> Podd n) ->
    (oddb n = false -> Peven n) ->
    combine_odd_even Podd Peven n.
Proof.
  intros podd peven n.
  unfold oddb.
  intros H1 H2.
  induction n as [|n'].
  unfold combine_odd_even. simpl. apply H2.  reflexivity.
  unfold combine_odd_even.
  destruct evenb.

    apply H2. reflexivity.
    apply H1. reflexivity.
Qed.

Theorem combine_odd_even_elim_odd :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = true ->
    Podd n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem combine_odd_even_elim_even :
  forall (Podd Peven : nat -> Prop) (n : nat),
    combine_odd_even Podd Peven n ->
    oddb n = false ->
    Peven n.
Proof.
  (* FILL IN HERE *) Admitted.

(** [] *)

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

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

(*
Fixpoint true_upto_n__true_everywhere
(* FILL IN HERE *)

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

(* $Date: 2014-06-05 07:22:21 -0400 (Thu, 05 Jun 2014) $ *)


(** * Logic: Logic in Coq *)

(*Require Export MoreCoq.
*)

(** Coq's built-in logic is very small: the only primitives are
    [Inductive] definitions, universal quantification ([forall]), and
    implication ([->]), while all the other familiar logical
    connectives -- conjunction, disjunction, negation, existential
    quantification, even equality -- can be encoded using just these.

    This chapter explains the encodings and shows how the tactics
    we've seen can be used to carry out standard forms of logical
    reasoning involving these connectives.

*)

(* ########################################################### *)
(** * Propositions *)

(** In previous chapters, we have seen many examples of factual
    claims (_propositions_) and ways of presenting evidence of their
    truth (_proofs_).  In particular, we have worked extensively with
    _equality propositions_ of the form [e1 = e2], with
    implications ([P -> Q]), and with quantified propositions
    ([forall x, P]).
*)

(** In Coq, the type of things that can (potentially)
    be proven is [Prop]. *)

(** Here is an example of a provable proposition: *)

Check (3 = 3).
(* ===> Prop *)

(** Here is an example of an unprovable proposition: *)

Check (forall (n:nat), n = 2).
(* ===> Prop *)

(** Recall that [Check] asks Coq to tell us the type of the indicated
  expression. *)

(* ########################################################### *)
(** * Proofs and Evidence *)

(** In Coq, propositions have the same status as other types, such as
    [nat].  Just as the natural numbers [0], [1], [2], etc. inhabit
    the type [nat], a Coq proposition [P] is inhabited by its
    _proofs_.  We will refer to such inhabitants as _proof term_ or
    _proof object_ or _evidence_ for the truth of [P].

    In Coq, when we state and then prove a lemma such as:

Lemma silly : 0 * 3 = 0.
Proof. reflexivity. Qed.

    the tactics we use within the [Proof]...[Qed] keywords tell Coq
    how to construct a proof term that inhabits the proposition.  In
    this case, the proposition [0 * 3 = 0] is justified by a
    combination of the _definition_ of [mult], which says that [0 * 3]
    _simplifies_ to just [0], and the _reflexive_ principle of
    equality, which says that [0 = 0].

*)

(** *** *)

Lemma silly : 0 * 3 = 0.
Proof. reflexivity. Qed.

(** We can see which proof term Coq constructs for a given Lemma by
using the [Print] directive: *)

Print silly.
(* ===> silly = eq_refl : 0 * 3 = 0 *)

(** Here, the [eq_refl] proof term witnesses the equality. (More on
equality later!)*)

(** ** Implications _are_ functions *)

(** Just as we can implement natural number multiplication as a
function:

[
mult : nat -> nat -> nat
]

The _proof term_ for an implication [P -> Q] is a _function_ that
takes evidence for [P] as input and produces evidence for [Q] as its
output.
*)

Lemma silly_implication : (1 + 1) = 2  ->  0 * 3 = 0.
Proof. intros H. reflexivity. Qed.

(** We can see that the proof term for the above lemma is indeed a
function: *)

Print silly_implication.
(* ===> silly_implication = fun _ : 1 + 1 = 2 => eq_refl
     : 1 + 1 = 2 -> 0 * 3 = 0 *)

(** ** Defining propositions *)

(** Just as we can create user-defined inductive types (like the
    lists, binary representations of natural numbers, etc., that we
    seen before), we can also create _user-defined_ propositions.

    Question: How do you define the meaning of a proposition?
*)

(** *** *)

(** The meaning of a proposition is given by _rules_ and _definitions_
    that say how to construct _evidence_ for the truth of the
    proposition from other evidence.

    - Typically, rules are defined _inductively_, just like any other
      datatype.

    - Sometimes a proposition is declared to be true without
      substantiating evidence.  Such propositions are called _axioms_.

    In this, and subsequence chapters, we'll see more about how these
    proof terms work in more detail.
*)

(* ########################################################### *)
(** * Conjunction (Logical "and") *)

(** The logical conjunction of propositions [P] and [Q] can be
    represented using an [Inductive] definition with one
    constructor. *)

Inductive and (P Q : Prop) : Prop :=
  conj : P -> Q -> (and P Q).

(** The intuition behind this definition is simple: to
    construct evidence for [and P Q], we must provide evidence
    for [P] and evidence for [Q].  More precisely:

    - [conj p q] can be taken as evidence for [and P Q] if [p]
      is evidence for [P] and [q] is evidence for [Q]; and

    - this is the _only_ way to give evidence for [and P Q] --
      that is, if someone gives us evidence for [and P Q], we
      know it must have the form [conj p q], where [p] is
      evidence for [P] and [q] is evidence for [Q].

   Since we'll be using conjunction a lot, let's introduce a more
   familiar-looking infix notation for it. *)

Notation "P /\ Q" := (and P Q) : type_scope.

(** (The [type_scope] annotation tells Coq that this notation
    will be appearing in propositions, not values.) *)

(** Consider the "type" of the constructor [conj]: *)

Check conj.
(* ===>  forall P Q : Prop, P -> Q -> P /\ Q *)

(** Notice that it takes 4 inputs -- namely the propositions [P]
    and [Q] and evidence for [P] and [Q] -- and returns as output the
    evidence of [P /\ Q]. *)

(** ** "Introducing" conjunctions *)
(** Besides the elegance of building everything up from a tiny
    foundation, what's nice about defining conjunction this way is
    that we can prove statements involving conjunction using the
    tactics that we already know.  For example, if the goal statement
    is a conjuction, we can prove it by applying the single
    constructor [conj], which (as can be seen from the type of [conj])
    solves the current goal and leaves the two parts of the
    conjunction as subgoals to be proved separately. *)

Theorem and_example :
  (0 = 0) /\ (4 = mult 2 2).
Proof.
  apply conj.
  (*Case "left".*) reflexivity.
  (*Case "right".*) reflexivity.  Qed.

(** Just for convenience, we can use the tactic [split] as a shorthand for
    [apply conj]. *)

Theorem and_example' :
  (0 = 0) /\ (4 = mult 2 2).
Proof.
  split.
    (*Case "left".*) reflexivity.
    (*Case "right".*) reflexivity.  Qed.

(** ** "Eliminating" conjunctions *)
(** Conversely, the [destruct] tactic can be used to take a
    conjunction hypothesis in the context, calculate what evidence
    must have been used to build it, and add variables representing
    this evidence to the proof context. *)

Theorem proj1 : forall P Q : Prop,
  P /\ Q -> P.
Proof.
  intros P Q H.
  destruct H as [HP HQ].
  apply HP.  Qed.

(** **** Exercise: 1 star, optional (proj2)  *)
Theorem proj2 : forall P Q : Prop,
  P /\ Q -> Q.
Proof.
  intros. destruct H as [HP HQ].
  apply HQ.
Qed.
(** [] *)

Theorem and_commut : forall P Q : Prop,
  P /\ Q -> Q /\ P.
Proof.
  (* WORKED IN CLASS *)
  intros P Q H.
  destruct H as [HP HQ].
  split.
    (*Case "left".*) apply HQ.
    (*Case "right".*) apply HP.  Qed.

(** **** Exercise: 2 stars (and_assoc)  *)
(** In the following proof, notice how the _nested pattern_ in the
    [destruct] breaks the hypothesis [H : P /\ (Q /\ R)] down into
    [HP: P], [HQ : Q], and [HR : R].  Finish the proof from there: *)

Theorem and_assoc : forall P Q R : Prop,
  P /\ (Q /\ R) -> (P /\ Q) /\ R.
Proof.
  intros P Q R H.
  destruct H as [HP [HQ HR]].
  split. split. apply HP. apply HQ. apply HR.
Qed.
(** [] *)

(* ###################################################### *)
(** * Iff *)

(** The handy "if and only if" connective is just the conjunction of
    two implications. *)

Definition iff (P Q : Prop) := (P -> Q) /\ (Q -> P).

Notation "P <-> Q" := (iff P Q)
                      (at level 95, no associativity)
                      : type_scope.

Theorem iff_implies : forall P Q : Prop,
  (P <-> Q) -> P -> Q.
Proof.
  intros P Q H.
  destruct H as [HAB HBA]. apply HAB.  Qed.

Theorem iff_sym : forall P Q : Prop,
  (P <-> Q) -> (Q <-> P).
Proof.
  (* WORKED IN CLASS *)
  intros P Q H.
  destruct H as [HAB HBA].
  split.
    (*Case "->".*) apply HBA.
    (*Case "<-".*) apply HAB.  Qed.

(** **** Exercise: 1 star, optional (iff_properties)  *)
(** Using the above proof that [<->] is symmetric ([iff_sym]) as
    a guide, prove that it is also reflexive and transitive. *)

Theorem iff_refl : forall P : Prop,
  P <-> P.
Proof.
  intros. split. intros. apply H.
  intros. apply H.
Qed.

Theorem iff_trans : forall P Q R : Prop,
  (P <-> Q) -> (Q <-> R) -> (P <-> R).
Proof.
  intros. split. destruct H. destruct H0.
  intros. apply H0. apply H. apply H3.
  intros. destruct H. destruct H0.
  apply H2. apply H3. apply H1.
Qed.

(** Hint: If you have an iff hypothesis in the context, you can use
    [inversion] to break it into two separate implications.  (Think
    about why this works.) *)
(** [] *)

(** Some of Coq's tactics treat [iff] statements specially, thus
    avoiding the need for some low-level manipulation when reasoning
    with them.  In particular, [rewrite] can be used with [iff]
    statements, not just equalities. *)

(* ############################################################ *)
(** * Disjunction (Logical "or") *)

(** ** Implementing disjunction *)

(** Disjunction ("logical or") can also be defined as an
    inductive proposition. *)

Inductive or (P Q : Prop) : Prop :=
  | or_introl : P -> or P Q
  | or_intror : Q -> or P Q.

Notation "P \/ Q" := (or P Q) : type_scope.

(** Consider the "type" of the constructor [or_introl]: *)

Check or_introl.
(* ===>  forall P Q : Prop, P -> P \/ Q *)

(** It takes 3 inputs, namely the propositions [P], [Q] and
    evidence of [P], and returns, as output, the evidence of [P \/ Q].
    Next, look at the type of [or_intror]: *)

Check or_intror.
(* ===>  forall P Q : Prop, Q -> P \/ Q *)

(** It is like [or_introl] but it requires evidence of [Q]
    instead of evidence of [P]. *)

(** Intuitively, there are two ways of giving evidence for [P \/ Q]:

    - give evidence for [P] (and say that it is [P] you are giving
      evidence for -- this is the function of the [or_introl]
      constructor), or

    - give evidence for [Q], tagged with the [or_intror]
      constructor. *)

(** *** *)
(** Since [P \/ Q] has two constructors, doing [destruct] on a
    hypothesis of type [P \/ Q] yields two subgoals. *)

Theorem or_commut : forall P Q : Prop,
  P \/ Q  -> Q \/ P.
Proof.
  intros P Q H.
  destruct H as [HP | HQ].
    (*Case "left".*) apply or_intror. apply HP.
    (*Case "right".*) apply or_introl. apply HQ.  Qed.

(** From here on, we'll use the shorthand tactics [left] and [right]
    in place of [apply or_introl] and [apply or_intror]. *)

Theorem or_commut' : forall P Q : Prop,
  P \/ Q  -> Q \/ P.
Proof.
  intros P Q H.
  destruct H as [HP | HQ].
    (*Case "left".*) right. apply HP.
    (*Case "right".*) left. apply HQ.  Qed.

Theorem or_distributes_over_and_1 : forall P Q R : Prop,
  P \/ (Q /\ R) -> (P \/ Q) /\ (P \/ R).
Proof.
  intros P Q R. intros H. destruct H as [HP | [HQ HR]].
    (*Case "left".*) split.
      (*SCase "left".*) left. apply HP.
      (*SCase "right".*) left. apply HP.
    (*Case "right".*) split.
      (*SCase "left".*) right. apply HQ.
      (*SCase "right".*) right. apply HR.  Qed.

(** **** Exercise: 2 stars (or_distributes_over_and_2)  *)
Theorem or_distributes_over_and_2 : forall P Q R : Prop,
  (P \/ Q) /\ (P \/ R) -> P \/ (Q /\ R).
Proof.
  intros. inversion H as [HPQ HPR]. inversion HPQ. left. apply H0.
  inversion HPR. left. apply H1.
  right. split. apply H0. apply H1.
Qed.
(** [] *)

(** **** Exercise: 1 star, optional (or_distributes_over_and)  *)
Theorem or_distributes_over_and : forall P Q R : Prop,
  P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  intros. split. apply or_distributes_over_and_1.
  apply or_distributes_over_and_2.
Qed.
(** [] *)

(* ################################################### *)
(** ** Relating [/\] and [\/] with [andb] and [orb] *)

(** We've already seen several places where analogous structures
    can be found in Coq's computational ([Type]) and logical ([Prop])
    worlds.  Here is one more: the boolean operators [andb] and [orb]
    are clearly analogs of the logical connectives [/\] and [\/].
    This analogy can be made more precise by the following theorems,
    which show how to translate knowledge about [andb] and [orb]'s
    behaviors on certain inputs into propositional facts about those
    inputs. *)

Theorem andb_prop : forall b c,
  andb b c = true -> b = true /\ c = true.
Proof.
  (* WORKED IN CLASS *)
  intros b c H.
  destruct b.
    (*Case "b = true".*) destruct c.
      (*SCase "c = true".*) apply conj. reflexivity. reflexivity.
      (*SCase "c = false".*) inversion H.
    (*Case "b = false".*) inversion H.  Qed.

Theorem andb_true_intro : forall b c,
  b = true /\ c = true -> andb b c = true.
Proof.
  (* WORKED IN CLASS *)
  intros b c H.
  destruct H.
  rewrite H. rewrite H0. reflexivity. Qed.

(** **** Exercise: 2 stars, optional (andb_false)  *)
Theorem andb_false : forall b c,
  andb b c = false -> b = false \/ c = false.
Proof.
  intros. destruct b.
  destruct c. inversion H.
  right. reflexivity.
  left. reflexivity.
Qed.

(** **** Exercise: 2 stars, optional (orb_false)  *)
Theorem orb_prop : forall b c,
  orb b c = true -> b = true \/ c = true.
Proof.
  intros. destruct b. left. reflexivity.
  destruct c. right. reflexivity.
  left. inversion H.
Qed.

(** **** Exercise: 2 stars, optional (orb_false_elim)  *)
Theorem orb_false_elim : forall b c,
  orb b c = false -> b = false /\ c = false.
Proof.
  intros. destruct b. destruct c. inversion H.
  split. inversion H. reflexivity.
  destruct c. split. reflexivity. inversion H.
  split. auto. auto.
Qed.
(** [] *)

(* ################################################### *)
(** * Falsehood *)

(** Logical falsehood can be represented in Coq as an inductively
    defined proposition with no constructors. *)

Inductive False : Prop := .

(** Intuition: [False] is a proposition for which there is no way
    to give evidence. *)

(** Since [False] has no constructors, inverting an assumption
    of type [False] always yields zero subgoals, allowing us to
    immediately prove any goal. *)

Theorem False_implies_nonsense :
  False -> 2 + 2 = 5.
Proof.
  intros contra.
  inversion contra.  Qed.

(** How does this work? The [inversion] tactic breaks [contra] into
    each of its possible cases, and yields a subgoal for each case.
    As [contra] is evidence for [False], it has _no_ possible cases,
    hence, there are no possible subgoals and the proof is done. *)

(** *** *)
(** Conversely, the only way to prove [False] is if there is already
    something nonsensical or contradictory in the context: *)

Theorem nonsense_implies_False :
  2 + 2 = 5 -> False.
Proof.
  intros contra.
  inversion contra.  Qed.

(** Actually, since the proof of [False_implies_nonsense]
    doesn't actually have anything to do with the specific nonsensical
    thing being proved; it can easily be generalized to work for an
    arbitrary [P]: *)

Theorem ex_falso_quodlibet : forall (P:Prop),
  False -> P.
Proof.
  (* WORKED IN CLASS *)
  intros P contra.
  inversion contra.  Qed.

(** The Latin _ex falso quodlibet_ means, literally, "from
    falsehood follows whatever you please."  This theorem is also
    known as the _principle of explosion_. *)

(* #################################################### *)
(** ** Truth *)

(** Since we have defined falsehood in Coq, one might wonder whether
    it is possible to define truth in the same way.  We can. *)

(** **** Exercise: 2 stars, advanced (True)  *)
(** Define [True] as another inductively defined proposition.  (The
    intution is that [True] should be a proposition for which it is
    trivial to give evidence.) *)

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

(** However, unlike [False], which we'll use extensively, [True] is
    used fairly rarely. By itself, it is trivial (and therefore
    uninteresting) to prove as a goal, and it carries no useful
    information as a hypothesis. But it can be useful when defining
    complex [Prop]s using conditionals, or as a parameter to
    higher-order [Prop]s. *)

(* #################################################### *)
(** * Negation *)

(** The logical complement of a proposition [P] is written [not
    P] or, for shorthand, [~P]: *)

Definition not (P:Prop) := P -> False.

(** The intuition is that, if [P] is not true, then anything at
    all (even [False]) follows from assuming [P]. *)

Notation "~ x" := (not x) : type_scope.

Check not.
(* ===> Prop -> Prop *)

(** It takes a little practice to get used to working with
    negation in Coq.  Even though you can see perfectly well why
    something is true, it can be a little hard at first to get things
    into the right configuration so that Coq can see it!  Here are
    proofs of a few familiar facts about negation to get you warmed
    up. *)

Theorem not_False :
  ~ False.
Proof.
  unfold not. intros H. inversion H.  Qed.

(** *** *)
Theorem contradiction_implies_anything : forall P Q : Prop,
  (P /\ ~P) -> Q.
Proof.
  (* WORKED IN CLASS *)
  intros P Q H. destruct H as [HP HNA]. unfold not in HNA.
  apply HNA in HP. inversion HP.  Qed.

Theorem double_neg : forall P : Prop,
  P -> ~~P.
Proof.
  (* WORKED IN CLASS *)
  intros P H. unfold not. intros G. apply G. apply H.  Qed.

(** **** Exercise: 2 stars, advanced (double_neg_inf)  *)
(** Write an informal proof of [double_neg]:

   _Theorem_: [P] implies [~~P], for any proposition [P].

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

(** **** Exercise: 2 stars (contrapositive)  *)
Theorem contrapositive : forall P Q : Prop,
  (P -> Q) -> (~Q -> ~P).
Proof.
  intros. unfold not in H0. unfold not. intros. apply H0. apply H.
  apply H1.
Qed.
(** [] *)

(** **** Exercise: 1 star (not_both_true_and_false)  *)
Theorem not_both_true_and_false : forall P : Prop,
  ~ (P /\ ~P).
Proof.
  intros. unfold not. intros. destruct H.
  apply H0. apply H.
Qed.
(** [] *)

(** **** Exercise: 1 star, advanced (informal_not_PNP)  *)
(** Write an informal proof (in English) of the proposition [forall P
    : Prop, ~(P /\ ~P)]. *)

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

(** *** Constructive logic *)
(** Note that some theorems that are true in classical logic are _not_
    provable in Coq's (constructive) logic.  E.g., let's look at how
    this proof gets stuck... *)

Theorem classic_double_neg : forall P : Prop,
  ~~P -> P.
Proof.
  (* WORKED IN CLASS *)
  intros P H. unfold not in H.
  (* But now what? There is no way to "invent" evidence for [~P]
     from evidence for [P]. *)
  Abort.

(** **** Exercise: 5 stars, advanced, optional (classical_axioms)  *)
(** For those who like a challenge, here is an exercise
    taken from the Coq'Art book (p. 123).  The following five
    statements are often considered as characterizations of
    classical logic (as opposed to constructive logic, which is
    what is "built in" to Coq).  We can't prove them in Coq, but
    we can consistently add any one of them as an unproven axiom
    if we wish to work in classical logic.  Prove that these five
    propositions are equivalent. *)

Definition peirce := forall P Q: Prop,
  ((P->Q)->P)->P.
Definition classic := forall P:Prop,
  ~~P -> P.
Definition excluded_middle := forall P:Prop,
  P \/ ~P.
Definition de_morgan_not_and_not := forall P Q:Prop,
  ~(~P /\ ~Q) -> P\/Q.
Definition implies_to_or := forall P Q:Prop,
  (P->Q) -> (~P\/Q).

(** [] *)

(** **** Exercise: 3 stars (excluded_middle_irrefutable)  *)
(** This theorem implies that it is always safe to add a decidability
axiom (i.e. an instance of excluded middle) for any _particular_ Prop [P].
Why? Because we cannot prove the negation of such an axiom; if we could,
we would have both [~ (P \/ ~P)] and [~ ~ (P \/ ~P)], a contradiction. *)

Theorem excluded_middle_irrefutable:  forall (P:Prop), ~ ~ (P \/ ~ P).
Proof.
  intros. unfold not. intros. apply H. right. intros. apply H.
  left. apply H0.
Qed.

(* ########################################################## *)
(** ** Inequality *)

(** Saying [x <> y] is just the same as saying [~(x = y)]. *)

Notation "x <> y" := (~ (x = y)) : type_scope.

(** Since inequality involves a negation, it again requires
    a little practice to be able to work with it fluently.  Here
    is one very useful trick.  If you are trying to prove a goal
    that is nonsensical (e.g., the goal state is [false = true]),
    apply the lemma [ex_falso_quodlibet] to change the goal to
    [False].  This makes it easier to use assumptions of the form
    [~P] that are available in the context -- in particular,
    assumptions of the form [x<>y]. *)

Theorem not_false_then_true : forall b : bool,
  b <> false -> b = true.
Proof.
  intros b H. destruct b.
  (*Case "b = true".*) reflexivity.
  (*Case "b = false".*)
    unfold not in H.
    apply ex_falso_quodlibet.
    apply H. reflexivity.   Qed.

(** *** *)

(** *** *)

(** *** *)

(** *** *)

(** *** *)

(** **** Exercise: 2 stars (false_beq_nat)  *)
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.

Theorem false_beq_nat : forall n m : nat,
     n <> m ->
     beq_nat n m = false.
Proof.
  induction n. destruct m. intros. apply ex_falso_quodlibet.
  unfold not in H. apply H. reflexivity.
  intros. unfold not in H. split.
  destruct m. intros. unfold not in H. split.
  simpl. intros. apply IHn. revert H. unfold not.
  intros. apply H. apply f_equal. apply H0.
Qed.

(** **** Exercise: 2 stars, optional (beq_nat_false)  *)
Theorem beq_nat_false : forall n m,
  beq_nat n m = false -> n <> m.
Proof.
  induction n. unfold not. intros. destruct m. inversion H.
  inversion H0.
  unfold not. intros. destruct m. inversion H0. inversion H. inversion H0.
  revert H2 H3. apply IHn.
Qed.
(** [] *)

(** $Date: 2014-12-31 11:17:56 -0500 (Wed, 31 Dec 2014) $ *)


From LF Require Export Induction.
Module NatList.

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

Check (pair 3 5) : natprod.

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)).

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

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.

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

Theorem surjective_pairing_stuck : forall (p : natprod),
  p = (fst p, snd p).
Proof.
  simpl. (* 啥也没有归约！ *)
Abort.

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

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.

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.

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

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

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

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

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

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

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

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

Notation "x ++ y" := (app x y)
                     (right associativity, at level 60).
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.

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.
Compute tl [0;1;0;2;3;0;0].
Fixpoint nonzeros (l:natlist) : natlist :=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match l with
  |[]=>[]
  |h::t => if h=0 then (nonzeros t) else [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
  |[]=>[]
  |h::t=> if evenb h then (oddmembers t) else [h]++(oddmembers t)
end.
Example test_oddmembers:
  oddmembers [0;1;0;2;3;0;0] = [1;3].
Proof.
  simpl. reflexivity.
Qed.

Fixpoint countoddmembers (l:natlist) : nat :=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match l with
  |[]=>0
  |h::t=> if evenb h then (countoddmembers t) else 1+(countoddmembers t)
end.
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.

Fixpoint alternate (l1 l2 : natlist) : natlist :=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match l1,l2 with
  |[],[] => []
  |[],_ => l2
  |_,[]=> l1
  |h1::t1 , h2::t2 => [h1;h2]++(alternate t1 t2)
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.

Definition bag := natlist.

(** * Boolean equality on [nat] *)

Fixpoint beq_nat n m : bool :=
  match n, m with
    | O, O => true
    | O, S _ => false
    | S _, O => false
    | S n1, S m1 => beq_nat n1 m1
  end.

Check beq_nat.

Fixpoint count (v:nat) (s:bag) : nat :=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match s with
  |[]=>0
  |h::t=>(if beq_nat h v then 1 else 0) + (count v t)
end.

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

Definition sum : bag -> bag -> bag :=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  app.
Example test_sum1: count 1 (sum [1;2;3] [1;4;1]) = 3.
Proof.
  simpl. reflexivity.
Qed.
Definition add (v:nat) (s:bag) : bag :=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match s with
  |[]=>[v]
  |h::t=>[v]++h::t
end.
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 s with
  |[]=>false
  |h::t=>if h=v then true else false
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.

Fixpoint remove_one (v:nat) (s:bag) : bag:=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match s with
  |[]=>[]
  |h::t=>if h=v then t else h::(remove_one v t)
end.
Example test_remove_one1:
  count 5 (remove_one 5 [2;1;5;4;1]) = 0.
Proof.
  simpl. reflexivity.
Qed.
Example test_remove_one2:
  count 5 (remove_one 5 [2;1;4;1]) = 0.
Proof.
  simpl. reflexivity.
Qed.
Example test_remove_one3:
  count 4 (remove_one 5 [2;1;4;5;1;4]) = 2.
Proof.
  simpl. reflexivity.
Qed.
Example test_remove_one4:
  count 5 (remove_one 5 [2;1;5;4;5;1;4]) = 1.
Proof.
  simpl. reflexivity.
Qed.
Fixpoint remove_all (v:nat) (s:bag) : bag:=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match s with
  |[]=>[]
  |h::t=>if h=v then (remove_all v t) else h::(remove_all v t)
end.
Example test_remove_all1: count 5 (remove_all 5 [2;1;5;4;1]) = 0.
Proof.
  simpl. reflexivity.
Qed.
Example test_remove_all2: count 5 (remove_all 5 [2;1;4;1]) = 0.
Proof.
  simpl. reflexivity.
Qed.
Example test_remove_all3: count 4 (remove_all 5 [2;1;4;5;1;4]) = 2.
Proof.
  simpl. reflexivity.
Qed.
Example test_remove_all4: count 5 (remove_all 5 [2;1;5;4;5;1;4;5;1;4]) = 0.
Proof.
  simpl. reflexivity.
Qed.

Fixpoint subset (s1:bag) (s2:bag) : bool:=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match s1 with
  |[]=>true
  |h::t=>if (count h s2)=0 then false
                           else subset t (remove_one h s2)
end.
Example test_subset1: subset [1;2] [2;1;4;1] = true.
Proof.
  simpl. reflexivity.
Qed.
Example test_subset2: subset [1;2;2] [2;1;4;1] = false.
Proof.
  simpl. reflexivity.
Qed.

Theorem bag_count_add : forall s : bag,
  count 1 (add 1 s) = S (count 1 s).
Proof.
  intros s. destruct s as [].
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

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

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.

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.

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.

Theorem rev_length_firsttry : forall l : natlist,
  length (rev l) = length l.
Proof.
  intros l. induction l as [| n l' IHl'].
  - (* l = nil *)
    reflexivity.
  - (* l = n :: l' *)
    (* 这种情况比较棘手。我们从一般的化简开始。 *)
    simpl.
    (* 现在我们好像卡住了：目标是要证明涉及 ++ 的等式，
       但是我们在上下文和全局环境下并没有任何有用的等式！
       通过用 IH 来重写目标，我们可以推进一点... *)
    rewrite <- IHl'.
    (* ...但也仅此而已。 *)
Abort.

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

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.
    simpl. rewrite -> IHl'. rewrite plus_comm.
    reflexivity.
Qed.

Search app.

Theorem app_nil_r : forall l : natlist,
  l ++ [] = l.
Proof.
  (* 请在此处解答 *)
  intros l. induction l as [].
  - 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 [].
  - simpl. rewrite -> app_nil_r. reflexivity.
  - simpl. rewrite -> IHl1. rewrite -> app_assoc. reflexivity.
Qed.
Theorem rev_involutive : forall l : natlist,
  rev (rev l) = l.
Proof.
  (* 请在此处解答 *)
  intros l. induction l as [].
  - simpl. reflexivity.
  - simpl. rewrite -> rev_app_distr. simpl.
    rewrite -> IHl. reflexivity.
Qed.

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.

Search nonzeros.

Lemma nonzeros_app : forall l1 l2 : natlist,
  nonzeros (l1 ++ l2) = (nonzeros l1) ++ (nonzeros l2).
Proof.
  (* 请在此处解答 *)
  intros l1 l2. induction l1 as [].
  - simpl. reflexivity.
  - simpl. rewrite -> IHl1.
    destruct n as [].
    * simpl. reflexivity.
    * simpl. reflexivity.
Qed.

Fixpoint eqblist (l1 l2 : natlist) : bool:=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match l1,l2 with
  |[],[]=>true
  |[],_ =>false
  |_ ,[]=>false
  |h1::t1,h2::t2=>if h1=h2 then eqblist t1 t2
                           else false
end.
Example test_eqblist1 :
  (eqblist nil nil = true).
 (* 请在此处解答 *)
Proof.
  reflexivity.
Qed.
Example test_eqblist2 :
  eqblist [1;2;3] [1;2;3] = true.
(* 请在此处解答 *)
Proof.
  reflexivity.
Qed.
Example test_eqblist3 :
  eqblist [1;2;3] [1;2;4] = false.
 (* 请在此处解答 *) Proof.
  reflexivity.
Qed.
Theorem eqblist_refl : forall l:natlist,
  true = eqblist l l.
Proof.
  intros l. induction l as [].
  - simpl. reflexivity.
  - simpl. induction n as [].
    * simpl. rewrite <- IHl. reflexivity.
    * simpl. rewrite <- IHn. reflexivity.
Qed.

Theorem count_member_nonzero : forall (s : bag),
  (1 <= (count 1 (1 :: s))) = true.
Proof.
  (* 请在此处解答 *)
  intros s. simpl. reflexivity.
Qed.

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

Theorem remove_does_not_increase_count: forall (s : bag),
  ((count 0 (remove_one 0 s)) <= (count 0 s)) = true.
Proof.
  (* 请在此处解答 *)
  intros s. induction s as [].
  - simpl. reflexivity.
  - simpl. induction n as [].
    * simpl. rewrite -> leb_n_Sn. reflexivity.
    * simpl. rewrite -> IHs. reflexivity.
Qed.

(*Theorem app_nil_r : forall l : natlist,
  l ++ [] = l.*)
Theorem bag_count_sum : forall (n : nat) (s1 s2 : bag),
  count n (sum s1 s2) = count n s1 + count n s2.
Proof.
  intros n s1 s2. induction s1 as [|h1 t1 IHs1].
  - simpl. reflexivity.
  - induction s2 as [|h2 t2 IHs2].
    * simpl. rewrite <- plus_n_O. rewrite -> app_nil_r. reflexivity.
    * simpl. rewrite -> IHs1. simpl. rewrite -> plus_assoc. reflexivity.
Qed.

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

Fixpoint nth_bad (l:natlist) (n:nat) : nat :=
  match l with
  | nil => 42
  | a :: l' => match n with
               | 0 => a
               | S n' => nth_bad l' n'
               end
  end.

Compute nth_bad [1;4;5;6] 4.

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

Fixpoint nth_error (l:natlist) (n:nat) : natoption :=
  match l with
  | nil => None
  | a :: l' => match n with
               | O => Some a
               | S n' => nth_error l' n'
               end
  end.
Example test_nth_error1 : nth_error [4;5;6;7] 0 = Some 4.
Proof.
  simpl. reflexivity.
Qed.
Example test_nth_error2 : nth_error [4;5;6;7] 3 = Some 7.
Proof.
  simpl. reflexivity.
Qed.
Example test_nth_error3 : nth_error [4;5;6;7] 9 = None.
Proof.
  simpl. reflexivity.
Qed.

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

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

(*Definition hd (default:nat) (l:natlist) : nat :=
  match l with
  | nil => default
  | h :: t => h
  end.*)
Definition hd_error (l : natlist) : natoption :=
  (* 将本行替换成 ":= _你的_定义_ ." *)
  match l with
  | nil => None
  | a::l => Some a
end.
Example test_hd_error1 : hd_error [] = None.
Proof.
  simpl. reflexivity.
Qed.
Example test_hd_error2 : hd_error [1] = Some 1.
Proof.
  simpl. reflexivity.
Qed.
Example test_hd_error3 : hd_error [5;6] = Some 5.
Proof.
  simpl. reflexivity.
Qed.

Theorem option_elim_hd : forall (l:natlist) (default:nat),
  hd default l = option_elim default (hd_error l).
Proof.
  (* 请在此处解答 *)
  intros l default. destruct l as [].
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.
End NatList.

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

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

Compute eqb_id (Id 2) (Id 2).

Theorem eqb_id_refl : forall x, true = eqb_id x x.
Proof.
  (* 请在此处解答 *)
  intros x. destruct x as []. simpl.
  induction n as [].
  - simpl. reflexivity.
  - simpl. rewrite <- IHn. reflexivity.
Qed.

Module PartialMap.
Export NatList.

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

Check record (Id 1) 4 empty.

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

Compute update (record (Id 1) 1 empty) (Id 2) 2.

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

Theorem update_eq :
  forall (d : partial_map) (x : id) (v: nat),
    find x (update d x v) = Some v.
Proof.
  intros d x v.
  simpl. rewrite <- eqb_id_refl. reflexivity.
Qed.

Theorem update_neq :
  forall (d : partial_map) (x y : id) (o: nat),
    eqb_id x y = false -> find x (update d y o) = find x d.
Proof.
  intros d x y o eq.
  simpl. rewrite -> eq. reflexivity.
Qed.

End PartialMap.

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