(* Code for Software Foundations, Chapter 7: Logic: Logic in Coq *)

Require Import Arith.
Require Import Arith.Even.
Require Import List.
Require Import Coq.Setoids.Setoid.
Require Import Coq.Logic.FunctionalExtensionality.
Require Import Poly.
Require Import Tactics.

(* and_exercise *)

Example and_exercise :
  forall n m : nat, n + m = O -> n = O /\ m = O.
Proof.
  induction n, m.
  + simpl; intros; split; assumption.
  + simpl; intros; split; [reflexivity | assumption].
  + simpl; inversion 1.
  + simpl; inversion 1.
Qed.

(* and_assoc *)

Theorem and_assoc :
  forall P Q R : Prop, P /\ (Q /\ R) -> (P /\ Q) /\ R.
Proof.
  intros P Q R [p [q r]].
  repeat split; assumption.
Qed.

(* mult_eq_O *)

Theorem mult_eq_O :
  forall n m, n * m = O -> n = 0 \/ m = 0.
Proof.
  induction n, m.
  + simpl; left; reflexivity.
  + simpl; left; reflexivity.
  + simpl; right; reflexivity.
  + simpl; inversion 1.
Qed.

(* or_commut *)

Theorem or_commut :
  forall P Q, P \/ Q -> Q \/ P.
Proof.
  intros P Q [p | q].
  + right; assumption.
  + left; assumption.
Qed.

(* ex_falso_quodlibet *)

Theorem ex_falso_quodlibet :
  forall P : Prop, False -> P.
Proof.
  intros P false.
  apply False_ind; assumption. (* or: "elim false." *)
Qed.

(* not_implies_our_not *)

Fact not_implies_our_not :
  forall P, ~ P -> (forall Q, P -> Q).
Proof.
  intros P negp Q p.
  elim negp; apply p.
Qed.

(* zero_not_one *)

Theorem zero_not_one :
  ~ (0 = 1).
Proof.
  intros contradiction.
  inversion contradiction.
Qed.

(* double_neg_inf *)

Theorem double_neg_inf :
  forall P : Prop, P -> ~ ~ P.
Proof.
  intros P p negp.
  elim negp; apply p.
Qed.

(* contrapositive *)

Theorem contrapositive :
  forall P Q : Prop, (P -> Q) -> (~ Q -> ~ P).
Proof.
  intros P Q h1 h2 h3.
  elim h2.
  apply h1; apply h3.
Qed.

(* not_both_true_and_false *)

Theorem not_both_true_and_false :
  forall P : Prop, ~ (P /\ ~ P).
Proof.
  intros P contradiction.
  inversion contradiction as [p negp].
  elim negp; apply p.
Qed.

(* iff_properties *)

Theorem iff_refl :
  forall P : Prop, P <-> P.
Proof.
  reflexivity.
Qed.

Theorem iff_trans :
  forall P Q R : Prop, (P <-> Q) -> (Q <-> R) -> (P <-> R).
Proof.
  intros P Q R h1 h2.
  split.
  + intros p.
    apply h2; apply h1; assumption.
  + intros r.
    apply h1; apply h2; assumption.
Qed.

(* or_distributes_over_and *)

Theorem or_distributes_over_and :
  forall P Q R : Prop, P \/ (Q /\ R) <-> (P \/ Q) /\ (P \/ R).
Proof.
  intros P Q R.
  split.
  + intros [p | [q r]].
    * split; left; assumption.
    * split; right; assumption.
  + intros [[p1 | q] [p2 | r]]. (* Important !! *)
    * left; assumption.
    * left; assumption.
    * left; assumption.
    * right; split; assumption.
Qed.

(* dist_not_exists *)

Theorem dist_not_exists :
  forall (X : Type) (P : X -> Prop), (
    forall x, P x) -> ~ (
      exists x, ~ P x).
Proof.
  intros X P h1 h2.
  elim h2.
  intros x h3.
  elim h3.
  apply h1.
Qed.

(* dist_exists_or *)

Theorem dist_exists_or :
  forall (X : Type) (P Q : X -> Prop), (
    exists x, P x \/ Q x) <-> (
      exists x, P x) \/ (
        exists x, Q x).
Proof.
  intros X P Q.
  split.
  + intros h1.
    elim h1.
    intros x [hp | hq].
    - left; exists x; assumption.
    - right; exists x; assumption.
  + intros [hp | hq].
    - elim hp.
      intros x p.
      exists x; left; assumption.
    - elim hq.
      intros x p.
      exists x; right; assumption.
Qed.

(* in_application *)

Fixpoint In {A : Type} (x : A) (l : list A) : Prop :=
  match l with
    | nil   => False
    | t::ts => x = t \/ In x ts
  end.

(* in_map_iff *)

Lemma in_map :
  forall (A B : Type) (f : A -> B) (l : list A) (x : A),
    In x l -> In (f x) (map f l).
Proof.
  induction l.
  + simpl; trivial.
  + simpl.
    intros x [hx_eq_a | hx_in_l].
    - left; rewrite hx_eq_a; reflexivity.
    - right; apply IHl; assumption.
Qed.

Lemma in_map_iff :
  forall (A B : Type) (f : A -> B) (l : list A) (y : B),
    In y (map f l) <->
      exists x, f x = y /\ In x l.
Proof.
  intros A B f l y.
  split.
  + intros h1.
    induction l as [|x l].
    - simpl in h1.
      elim h1.
    - induction h1 as [|h1].
      * exists x.
        split;
          [ rewrite H
          | simpl; left
          ]; reflexivity.
      * apply IHl in h1.
        destruct h1 as [x' h1].
        exists x'.
        split;
          [ apply h1
          | simpl; right; apply h1
          ].
  + intros [x [h1 h2]].
    simpl.
    induction l as [|a l].
    - simpl.
      inversion h2.
    - simpl in h2.
      destruct h2 as [h2l | h2r].
      * simpl.
        rewrite h2l in h1.
        rewrite h1.
        left; reflexivity.
      * simpl.
        right; apply IHl; apply h2r.
Qed.

(* in_app_iff *)

Lemma logic_or_comm :
  forall A B C D : Prop, A \/ B \/ C \/ D -> (A \/ B) \/ C \/ D.
Proof.
  intros A B C D [a | [b | [c | d]]].
  + left; left; assumption.
  + left; right; assumption.
  + right; left; assumption.
  + right; right; assumption.
Qed.

Lemma in_app_iff :
  forall A l l' (a : A), In a (l ++ l') <-> In a l \/ In a l'.
Proof.
  split; induction l, l'.
  + simpl. inversion 1.
  + simpl.
    intros h1.
    right; assumption.
  + simpl.
    intros [h1 | h2].
    * left; left; assumption.
    * apply IHl in h2.
      destruct h2 as [h3 | h4].
      - left; right; assumption.
      - inversion h4.
  + simpl.
    simpl in IHl.
    intros [h1 | h2].
    * left; left; assumption.
    * apply IHl in h2.
      destruct h2 as [h3 | [h4 | h5]].
      - left; right; assumption.
      - right; left; assumption.
      - right; right; assumption.
  + intros [h1 | h2].
    * inversion h1.
    * inversion h2.
  + simpl.
    intros [h1 | [h2 | h3]].
    * inversion h1.
    * left; assumption.
    * right; assumption.
  + simpl.
    intros [[h1 | h2] | h3].
    * left; assumption.
    * right; rewrite app_nil_r; assumption.
    * inversion h3.
  + simpl.
    intros [[h1 | h2] | [h3 | h4]].
    * left; assumption.
    * right.
      apply IHl.
      left; assumption.
    * right.
      apply IHl.
      simpl.
      right; left; assumption.
    * right.
      apply IHl.
      simpl.
      right; right; assumption.
Qed.

(* all *)

Fixpoint All {T} (P : T -> Prop) (l : list T) : Prop :=
  match l with
    | nil   => True
    | x::xs => P x /\ All P xs
  end.

Lemma All_In :
  forall T (P : T -> Prop) (l : list T), (
    forall x, In x l -> P x) <-> All P l.
Proof.
  split; induction l as [|a l].
  + intros h1.
    simpl; trivial.
  + simpl.
    intros h1.
    split.
    - apply h1.
      left; reflexivity.
    - apply IHl.
      intros x h2.
      apply h1.
      right; assumption.
  + intros h1 x h2.
    inversion h2.
  + simpl.
    intros [h1 h2] x [h3 | h4].
    - rewrite h3; assumption.
    - apply IHl; assumption.
Qed.

(* combine_odd_even *)

Definition combine_odd_even (P Q : nat -> Prop) : nat -> Prop :=
  fun (x : nat) => match Nat.even x with
    | true  => P x
    | false => Q x
  end.

Theorem combine_odd_even_intro :
  forall (P Q : nat -> Prop) (n : nat),
    (Nat.even n = true -> P n)
      -> (Nat.even n = false -> Q n)
        -> combine_odd_even P Q n.
Proof.
  intros P Q n h1 h2.
  unfold combine_odd_even.
  destruct (Nat.even n).
  + apply h1; reflexivity.
  + apply h2; reflexivity.
Qed.

Theorem combine_odd_even_elim_odd :
  forall (P Q : nat -> Prop) (n : nat),
    combine_odd_even P Q n -> Nat.even n = true -> P n.
Proof.
  intros P Q n h1 h2.
  unfold combine_odd_even in h1.
  destruct (Nat.even n).
  + assumption.
  + inversion h2.
Qed.

Theorem combine_odd_even_elim_even :
  forall (P Q : nat -> Prop) (n : nat),
    combine_odd_even P Q n -> Nat.even n = false -> Q n.
Proof.
  intros P Q n h1 h2.
  unfold combine_odd_even in h1.
  destruct (Nat.even n).
  + inversion h2.
  + assumption.
Qed.

(* tr_rev *)

Fixpoint tr_rev_aux {X} (l1 l2 : list X) : list X :=
  match l1 with
    | nil    => l2
    | x::l1' => tr_rev_aux l1' (x::l2)
  end.

Definition tr_rev {X} (l : list X) : list X :=
  tr_rev_aux l nil.

Lemma tr_rev_aux_correct :
  forall (X : Type) (l1 l2 : list X), tr_rev_aux l1 l2 = tr_rev_aux l1 nil ++ l2.
Proof.
  induction l1 as [|a l1].
  + simpl; reflexivity.
  + intros l2.
    simpl.
    rewrite (IHl1 (a::nil)).
    rewrite (IHl1 (a::l2)).
    rewrite <- app_assoc.
    simpl; reflexivity.
Qed.

Theorem tr_rev_correct :
  forall X, @tr_rev X = @rev X.
Proof.
  intros X.
  apply functional_extensionality.
  unfold tr_rev.
  induction x as [|x l].
  + simpl; reflexivity.
  + simpl.
    rewrite <- IHl.
    apply tr_rev_aux_correct.
Qed.

(* evenb_double *)

Lemma succ_transfer :
  forall n : nat, n + S (S n) = S n + S n.
Proof.
  induction n as [|n].
  + reflexivity.
  + simpl.
    rewrite Nat.add_succ_r.
    reflexivity.
Qed.

Theorem evenb_double :
  forall k, Nat.even (Nat.double k) = true.
Proof.
  induction k as [|k].
  + reflexivity.
  + simpl.
    destruct k as [|k'] eqn:k_ind.
    - simpl; reflexivity.
    - simpl.
      rewrite succ_transfer.
      apply IHk.
Qed.

(* evenb_double_conv *)

Theorem evenb_double_conv :
  forall n,
    exists k, n = if Nat.even n
      then Nat.double k
      else S (Nat.double k).
Proof.
  induction n as [|n].
  + exists O; reflexivity.
  + rewrite Nat.even_succ. (* The KEY step. *)
    destruct IHn as [x IHx].
    destruct (Nat.even n) eqn:x_odd_even.
    - exists x.
      rewrite <- IHx.
      assert (n_odd_even : Nat.even n = true -> Nat.odd n = false).
      * unfold Nat.odd; intros h1; rewrite h1; reflexivity.
      * rewrite n_odd_even;
          [ reflexivity
          | assumption
          ].
    - exists (S x).
      assert (n_odd_even : Nat.even n = false -> Nat.odd n = true).
      * unfold Nat.odd; intros h1; rewrite h1; reflexivity.
      * { rewrite n_odd_even.
          + rewrite IHx; unfold Nat.double.
            simpl.
            apply eq_S; rewrite Nat.add_succ_r; reflexivity.
          + assumption.
        }
Qed.

(* even_bool_prop *)

Theorem even_bool_prop :
  forall n, Nat.even n = true <->
    exists k, n = Nat.double k.
Proof.
  intros n.
  split.
  + intros h1.
    destruct (evenb_double_conv n) as [k Hk]. (* The KEY step. *)
    rewrite Hk.
    exists k.
    rewrite h1; reflexivity.
  + intros [k Hk].
    rewrite Hk.
    apply evenb_double.
Qed.

(* beq_nat_true_iff *)

Theorem beq_nat_true_iff :
  forall n1 n2, beq_nat n1 n2 = true <-> n1 = n2.
Proof.
  split.
  + apply beq_nat_true.
  + intros h1.
    rewrite h1.
    rewrite <- beq_nat_refl; reflexivity.
Qed.

(* logical_connectives *)

Theorem andb_true_iff :
  forall b1 b2 : bool, andb b1 b2 = true <-> b1 = true /\ b2 = true.
Proof.
  split.
  + induction b1, b2.
    - simpl; split; reflexivity.
    - simpl; split; [reflexivity | assumption].
    - simpl; split; [assumption | reflexivity].
    - simpl; split; assumption.
  + intros [h1 h2].
    rewrite h1; rewrite h2; simpl; reflexivity.
Qed.

Theorem orb_true_iff :
  forall b1 b2 : bool, orb b1 b2 = true <-> b1 = true \/ b2 = true.
Proof.
  split.
  + induction b1, b2.
    - simpl; left; reflexivity.
    - simpl; left; reflexivity.
    - simpl; right; reflexivity.
    - inversion 1.
  + intros [h1 | h2].
    - rewrite h1; reflexivity.
    - rewrite h2.
      destruct b1.
      * reflexivity.
      * reflexivity.
Qed.

(* beq_nat_false_iff *)

Theorem beq_nat_false_iff :
  forall x y : nat, beq_nat x y = false <-> x <> y.
Proof.
  intros x y.
  split.
  + intros h1 h2.
    rewrite h2 in h1.
    rewrite <- beq_nat_refl in h1.
    inversion h1.
  + intros h1.
    destruct (beq_nat x y) eqn:x_eq_y.
    - apply beq_nat_true in x_eq_y.
      elim h1; assumption.
    - reflexivity.
Qed.

(* beq_list *)

Fixpoint beq_list {A : Type} (beq : A -> A -> bool) (l1 l2 : list A) : bool :=
  match l1, l2 with
    | nil, nil       => true
    | x::l1', y::l2' => beq x y && beq_list beq l1' l2'
    | _, _           => false
  end.

Theorem beq_list_true_iff :
  forall (A : Type) (beq : A -> A -> bool), (
    forall a1 a2, beq a1 a2 = true <-> a1 = a2) ->
      forall l1 l2, beq_list beq l1 l2 = true <-> l1 = l2.
Proof.
  intros A beq h1.
  induction l1 as [|a l1].
  + induction l2 as [|b l2].
    - split; reflexivity.
    - split; intros h2; inversion h2.
  + induction l2 as [|b l2].
    - split; inversion 1.
    - simpl; split.
      * intros h2.
        apply andb_true_iff in h2.
        destruct h2 as [h2 h3].
        apply h1 in h2.
        apply IHl1 in h3.
        rewrite h2; rewrite h3; reflexivity.
      * intros h2.
        apply andb_true_iff.
        injection h2 as h2 h3.
        rewrite h2; rewrite <- h3.
        split; [apply h1 | apply IHl1]; reflexivity.
Qed.

(* All_forallb *)

Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
    | nil   => true
    | x::l' => test x && forallb test l'
  end.

Theorem forallb_true_iff :
  forall X test (l : list X), forallb test l = true <-> All (fun x => test x = true) l.
Proof.
  induction l.
  + simpl; split; [ trivial | reflexivity ].
  + simpl; split.
    * intros h1; apply andb_true_iff in h1; destruct h1 as [h1 h2]; split.
      - assumption.
      - apply IHl; assumption.
    * intros [h1 h2].
      apply andb_true_iff.
      split.
      - assumption.
      - apply IHl in h2; assumption.
Qed.

(* restricted_excluded_middle *)

Definition excluded_middle := forall P : Prop, P \/ ~ P.

Theorem restricted_excluded_middle :
  forall P b, (P <-> b = true) -> P \/ ~ P.
Proof.
  intros P b h1.
  destruct b eqn:b_value.
  - left; apply h1; reflexivity.
  - right; rewrite h1; inversion 1.
Qed.

(* excluded_middle_irrefutable *)

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

(* not_exist_dist *)

Theorem not_exist_dist :
  excluded_middle ->
    forall (X : Type) (P : X -> Prop), ~ (
      exists x, ~ P x) -> (
        forall x, P x).
Proof.
  unfold excluded_middle.
  intros em X P h1 x.
  destruct (em (P x)) as [p | negp].
  + assumption.
  + elim h1.
    exists x; assumption.
Qed.


(** Formal Reasoning About Programs <http://adam.chlipala.net/frap/>
  * Chapter 8: Lambda Calculus and Simple Type Soundness
  * Author: Adam Chlipala
  * License: https://creativecommons.org/licenses/by-nc-nd/4.0/ *)

Require Import Frap.

(* The last few chapters have focused on small programming languages that are
 * representative of the essence of the imperative languages.  We now turn to
 * lambda-calculus, the usual representative of functional languages. *)

Module Ulc.
  Inductive exp : Set :=
  | Var (x : var)
  | Abs (x : var) (body : exp)
  | App (e1 e2 : exp).

  Fixpoint subst (rep : exp) (x : var) (e : exp) : exp :=
    match e with
    | Var y => if y ==v x then rep else Var y
    | Abs y e1 => Abs y (if y ==v x then e1 else subst rep x e1)
    | App e1 e2 => App (subst rep x e1) (subst rep x e2)
    end.

  (** * Big-step semantics *)

  Inductive eval : exp -> exp -> Prop :=
  | BigAbs : forall x e,
    eval (Abs x e) (Abs x e)
  | BigApp : forall e1 x e1' e2 v2 v,
    eval e1 (Abs x e1')
    -> eval e2 v2
    -> eval (subst v2 x e1') v
    -> eval (App e1 e2) v.

  Inductive value : exp -> Prop :=
  | Value : forall x e, value (Abs x e).

  Hint Constructors eval value.

  Theorem value_eval : forall v,
    value v
    -> eval v v.
  Proof.
    invert 1; eauto.
  Qed.

  Hint Resolve value_eval.

  Theorem eval_value : forall e v,
    eval e v
    -> value v.
  Proof.
    induct 1; eauto.
  Qed.

  Hint Resolve eval_value.

  (* Some notations, to let us write more normal-looking lambda terms *)
  Coercion Var : var >-> exp.
  Notation "\ x , e" := (Abs x e) (at level 50).
  Infix "@" := App (at level 49, left associativity).

  (* Believe it or not, this is a Turing-complete language!  Here's an example
   * nonterminating program. *)
  Example omega := (\"x", "x" @ "x") @ (\"x", "x" @ "x").

  (** * Church Numerals, everyone's favorite example of lambda terms in
      * action *)

  (* Here are two curious definitions. *)
  Definition zero := \"f", \"x", "x".
  Definition plus1 := \"n", \"f", \"x", "f" @ ("n" @ "f" @ "x").

  (* We can build up any natural number [n] as [plus1^n @ zero].  Let's prove
   * that, in fact, these definitions constitute a workable embedding of the
   * natural numbers in lambda-calculus. *)

  (* A term [plus^n @ zero] evaluates to something very close to what this
   * function returns. *)
  Fixpoint canonical' (n : nat) : exp :=
    match n with
    | O => "x"
    | S n' => "f" @ ((\"f", \"x", canonical' n') @ "f" @ "x")
    end.

  (* This missing piece is this wrapper. *)
  Definition canonical n := \"f", \"x", canonical' n.

  (* Let's formalize our definition of what it means to represent a number. *)
  Definition represents (e : exp) (n : nat) :=
    eval e (canonical n).

  (* Zero passes the test. *)
  Theorem zero_ok : represents zero 0.
  Proof.
    unfold zero, represents, canonical.
    simplify.
    econstructor.
  Qed.

  (* So does our successor operation. *)
  Theorem plus1_ok : forall e n, represents e n
                                 -> represents (plus1 @ e) (S n).
  Proof.
    unfold plus1, represents, canonical; simplify.
    econstructor.
    econstructor.
    eassumption.
    simplify.
    econstructor.
  Qed.

  (* What's basically going on here?  The representation of number [n] is [N]
   * such that, for any function [f]:
   *   N(f) = f^n
   * That is, we represent a number as its repeated-composition operator.
   * So, given a number, we can use it to repeat any operation.  In particular,
   * to implement addition, we can just repeat [plus1]! *)
  Definition add := \"n", \"m", "n" @ plus1 @ "m".

  (* Our addition works properly on this test case. *)
  Example add_1_2 : exists v,
      eval (add @ (plus1 @ zero) @ (plus1 @ (plus1 @ zero))) v
      /\ eval (plus1 @ (plus1 @ (plus1 @ zero))) v.
  Proof.
    eexists; propositional.
    repeat (econstructor; simplify).
    repeat econstructor.
  Qed.

  (* By the way: since [canonical'] doesn't mention variable "m", substituting
   * for "m" has no effect.  This fact will come in handy shortly. *)
  Lemma subst_m_canonical' : forall m n,
    subst m "m" (canonical' n) = canonical' n.
  Proof.
    induct n; simplify; equality.
  Qed.

  (* This inductive proof is the workhorse for the next result, so let's skip
   * ahead there. *)
  Lemma add_ok' : forall m n,
      eval
        (subst (\ "f", (\ "x", canonical' m)) "x"
               (subst (\ "n", (\ "f", (\ "x", "f" @ (("n" @ "f") @ "x")))) "f"
                      (canonical' n))) (canonical (n + m)).
  Proof.
    induct n; simplify.

    econstructor.

    econstructor.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    simplify.
    econstructor.
    econstructor.
    simplify.
    eassumption.

    simplify.
    econstructor.
  Qed.

  (* [add] properly encodes the usual addition. *)
  Theorem add_ok : forall n ne m me,
      represents ne n
      -> represents me m
      -> represents (add @ ne @ me) (n + m).
  Proof.
    unfold represents; simplify.

    econstructor.
    econstructor.
    econstructor.
    eassumption.
    simplify.
    econstructor.
    eassumption.
    simplify.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    simplify.
    econstructor.
    econstructor.
    rewrite subst_m_canonical'.
    apply add_ok'.
  Qed.

  (* Let's repeat the same exercise for multiplication. *)

  Definition mult := \"n", \"m", "n" @ (add @ "m") @ zero.

  Example mult_1_2 : exists v,
      eval (mult @ (plus1 @ zero) @ (plus1 @ (plus1 @ zero))) v
      /\ eval (plus1 @ (plus1 @ zero)) v.
  Proof.
    eexists; propositional.
    repeat (econstructor; simplify).
    repeat econstructor.
  Qed.

  Lemma mult_ok' : forall m n,
      eval
        (subst (\ "f", (\ "x", "x")) "x"
               (subst
                  (\ "m",
                   ((\ "f", (\ "x", canonical' m)) @
                                                   (\ "n", (\ "f", (\ "x", "f" @ (("n" @ "f") @ "x"))))) @ "m")
                  "f" (canonical' n))) (canonical (n * m)).
  Proof.
    induct n; simplify.

    econstructor.

    econstructor.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    simplify.
    econstructor.
    econstructor.
    simplify.
    eassumption.

    simplify.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    simplify.
    econstructor.
    econstructor.
    rewrite subst_m_canonical'.
    apply add_ok'. (* Note the recursive appeal to correctness of [add]. *)
  Qed.

  Theorem mult_ok : forall n ne m me,
      represents ne n
      -> represents me m
      -> represents (mult @ ne @ me) (n * m).
  Proof.
    unfold represents; simplify.

    econstructor.
    econstructor.
    econstructor.
    eassumption.
    simplify.
    econstructor.
    eassumption.
    simplify.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    econstructor.
    simplify.
    econstructor.
    simplify.
    econstructor.
    econstructor.
    simplify.
    rewrite subst_m_canonical'.
    apply mult_ok'.
  Qed.

  (** * Small-step semantics with evaluation contexts *)

  Inductive context : Set :=
  | Hole : context
  | App1 : context -> exp -> context
  | App2 : exp -> context -> context.

  Inductive plug : context -> exp -> exp -> Prop :=
  | PlugHole : forall e,
    plug Hole e e
  | PlugApp1 : forall c e1 e2 e,
    plug c e1 e
    -> plug (App1 c e2) e1 (App e e2)
  | PlugApp2 : forall c e1 e2 e,
    value e1
    -> plug c e2 e
    -> plug (App2 e1 c) e2 (App e1 e).

  Inductive step : exp -> exp -> Prop :=
  | ContextBeta : forall c x e v e1 e2,
    value v
    -> plug c (App (Abs x e) v) e1
    -> plug c (subst v x e) e2
    -> step e1 e2.

  Hint Constructors plug step.

  (* Here we now go through a proof of equivalence between big- and small-step
   * semantics, though we won't spend any further commentary on it. *)

  Lemma step_eval'' : forall v c x e e1 e2 v0,
    value v
    -> plug c (App (Abs x e) v) e1
    -> plug c (subst v x e) e2
    -> eval e2 v0
    -> eval e1 v0.
  Proof.
    induct c; invert 2; invert 1; simplify; eauto.
    invert H0; eauto.
    invert H0; eauto.
  Qed.

  Hint Resolve step_eval''.

  Lemma step_eval' : forall e1 e2,
    step e1 e2
    -> forall v, eval e2 v
      -> eval e1 v.
  Proof.
    invert 1; simplify; eauto.
  Qed.

  Hint Resolve step_eval'.

  Theorem step_eval : forall e v,
    step^* e v
    -> value v
    -> eval e v.
  Proof.
    induct 1; eauto.
  Qed.

  Lemma plug_functional : forall C e e1,
      plug C e e1
      -> forall e2, plug C e e2
                    -> e1 = e2.
  Proof.
    induct 1; invert 1; simplify; try f_equal; eauto.
  Qed.

  Lemma plug_mirror : forall C e e', plug C e e'
    -> forall e1, exists e1', plug C e1 e1'.
  Proof.
    induct 1; simplify; eauto.

    specialize (IHplug e0); first_order; eauto.

    specialize (IHplug e0); first_order; eauto.
  Qed.

  Fixpoint compose (C1 C2 : context) : context :=
    match C2 with
    | Hole => C1
    | App1 C2' e => App1 (compose C1 C2') e
    | App2 v C2' => App2 v (compose C1 C2')
    end.

  Lemma compose_ok : forall C1 C2 e1 e2 e3,
      plug C1 e1 e2
      -> plug C2 e2 e3
      -> plug (compose C1 C2) e1 e3.
  Proof.
    induct 2; simplify; eauto.
  Qed.

  Hint Resolve compose_ok.

  Lemma step_plug : forall e1 e2,
    step e1 e2
    -> forall C e1' e2', plug C e1 e1'
                         -> plug C e2 e2'
                         -> step e1' e2'.
  Proof.
    invert 1; simplify; eauto.
  Qed.

  Lemma stepStar_plug : forall e1 e2,
    step^* e1 e2
    -> forall C e1' e2', plug C e1 e1'
                         -> plug C e2 e2'
                         -> step^* e1' e2'.
  Proof.
    induct 1; simplify.

    assert (e1' = e2') by (eapply plug_functional; eassumption).
    subst.
    constructor.

    assert (exists y', plug C y y') by eauto using plug_mirror.
    invert H3.
    eapply step_plug in H.
    econstructor.
    eassumption.
    eapply IHtrc.
    eassumption.
    assumption.
    eassumption.
    assumption.
  Qed.

  Hint Resolve stepStar_plug eval_value.

  Theorem eval_step : forall e v,
    eval e v
    -> step^* e v.
  Proof.
    induct 1; eauto.

    eapply trc_trans.
    eapply stepStar_plug with (e1 := e1) (e2 := Abs x e1') (C := App1 Hole e2); eauto.
    eapply trc_trans.
    eapply stepStar_plug with (e1 := e2) (e2 := v2) (C := App2 (Abs x e1') Hole); eauto.
    eauto.
  Qed.
End Ulc.

Module Stlc.
  Inductive exp : Set :=
  | Var (x : var)
  | Const (n : nat)
  | Plus (e1 e2 : exp)
  | Abs (x : var) (e1 : exp)
  | App (e1 e2 : exp).

  Inductive value : exp -> Prop :=
  | VConst : forall n, value (Const n)
  | VAbs : forall x e1, value (Abs x e1).

  Fixpoint subst (e1 : exp) (x : string) (e2 : exp) : exp :=
    match e2 with
      | Var y => if y ==v x then e1 else Var y
      | Const n => Const n
      | Plus e2' e2'' => Plus (subst e1 x e2') (subst e1 x e2'')
      | Abs y e2' => Abs y (if y ==v x then e2' else subst e1 x e2')
      | App e2' e2'' => App (subst e1 x e2') (subst e1 x e2'')
    end.

  Inductive context : Set :=
  | Hole : context
  | Plus1 : context -> exp -> context
  | Plus2 : exp -> context -> context
  | App1 : context -> exp -> context
  | App2 : exp -> context -> context.

  Inductive plug : context -> exp -> exp -> Prop :=
  | PlugHole : forall e, plug Hole e e
  | PlugPlus1 : forall e e' C e2,
    plug C e e'
    -> plug (Plus1 C e2) e (Plus e' e2)
  | PlugPlus2 : forall e e' v1 C,
    value v1
    -> plug C e e'
    -> plug (Plus2 v1 C) e (Plus v1 e')
  | PlugApp1 : forall e e' C e2,
    plug C e e'
    -> plug (App1 C e2) e (App e' e2)
  | PlugApp2 : forall e e' v1 C,
    value v1
    -> plug C e e'
    -> plug (App2 v1 C) e (App v1 e').

  Inductive step0 : exp -> exp -> Prop :=
  | Beta : forall x e v,
    value v
    -> step0 (App (Abs x e) v) (subst v x e)
  | Add : forall n1 n2,
    step0 (Plus (Const n1) (Const n2)) (Const (n1 + n2)).

  Inductive step : exp -> exp -> Prop :=
  | StepRule : forall C e1 e2 e1' e2',
    plug C e1 e1'
    -> plug C e2 e2'
    -> step0 e1 e2
    -> step e1' e2'.

  Definition trsys_of (e : exp) := {|
    Initial := {e};
    Step := step
  |}.

  Inductive type :=
  | Nat                  (* Numbers *)
  | Fun (dom ran : type) (* Functions *).

  Inductive hasty : fmap var type -> exp -> type -> Prop :=
  | HtVar : forall G x t,
    G $? x = Some t
    -> hasty G (Var x) t
  | HtConst : forall G n,
    hasty G (Const n) Nat
  | HtPlus : forall G e1 e2,
    hasty G e1 Nat
    -> hasty G e2 Nat
    -> hasty G (Plus e1 e2) Nat
  | HtAbs : forall G x e1 t1 t2,
    hasty (G $+ (x, t1)) e1 t2
    -> hasty G (Abs x e1) (Fun t1 t2)
  | HtApp : forall G e1 e2 t1 t2,
    hasty G e1 (Fun t1 t2)
    -> hasty G e2 t1
    -> hasty G (App e1 e2) t2.

  Hint Constructors value plug step0 step hasty.

  (* Some notation to make it more pleasant to write programs *)
  Infix "-->" := Fun (at level 60, right associativity).
  Coercion Const : nat >-> exp.
  Infix "^+^" := Plus (at level 50).
  Coercion Var : var >-> exp.
  Notation "\ x , e" := (Abs x e) (at level 51).
  Infix "@" := App (at level 49, left associativity).

  (* Some examples of typed programs *)

  Example one_plus_one : hasty $0 (1 ^+^ 1) Nat.
  Proof.
    repeat (econstructor; simplify).
  Qed.

  Example add : hasty $0 (\"n", \"m", "n" ^+^ "m") (Nat --> Nat --> Nat).
  Proof.
    repeat (econstructor; simplify).
  Qed.

  Example eleven : hasty $0 ((\"n", \"m", "n" ^+^ "m") @ 7 @ 4) Nat.
  Proof.
    repeat (econstructor; simplify).
  Qed.

  Example seven_the_long_way : hasty $0 ((\"x", "x") @ (\"x", "x") @ 7) Nat.
  Proof.
    repeat (econstructor; simplify).
  Qed.

  (** * Let's prove type soundness. *)

  Definition unstuck e := value e
    \/ (exists e' : exp, step e e').

  Lemma progress : forall e t,
    hasty $0 e t
    -> value e
    \/ (exists e' : exp, step e e').
  Proof.
    induct 1; simplify; try equality.

    left.
    constructor.

    propositional.

    right.
    match goal with
    | [ H1 : value e1, H2 : hasty $0 e1 _ |- _ ] => invert H1; invert H2
    end.
    match goal with
    | [ H1 : value e2, H2 : hasty $0 e2 _ |- _ ] => invert H1; invert H2
    end.
    exists (Const (n + n0)).
    eapply StepRule with (C := Hole).
    eauto.
    eauto.
    constructor.

    match goal with
    | [ H : exists x, _ |- _ ] => invert H
    end.
    match goal with
    | [ H : step _ _ |- _ ] => invert H
    end.
    right.
    eauto.

    match goal with
    | [ H : exists x, _ |- _ ] => invert H
    end.
    match goal with
    | [ H : step _ _ |- _ ] => invert H
    end.
    right.
    eauto.

    match goal with
    | [ H : exists x, step e1 _ |- _ ] => invert H
    end.
    match goal with
    | [ H : step _ _ |- _ ] => invert H
    end.
    right.
    exists (Plus x e2).
    eapply StepRule with (C := Plus1 C e2).
    eauto.
    eauto.
    assumption.

    left.
    constructor.

    propositional.

    right.
    match goal with
    | [ H1 : value e1, H2 : hasty $0 e1 _ |- _ ] => invert H1; invert H2
    end.
    exists (subst e2 x e0).
    eapply StepRule with (C := Hole).
    eauto.
    eauto.
    constructor.
    assumption.

    match goal with
    | [ H : exists x, _ |- _ ] => invert H
    end.
    match goal with
    | [ H : step _ _ |- _ ] => invert H
    end.
    right.
    eauto.

    match goal with
    | [ H : exists x, _ |- _ ] => invert H
    end.
    match goal with
    | [ H : step _ _ |- _ ] => invert H
    end.
    right.
    eauto.

    match goal with
    | [ H : exists x, step e1 _ |- _ ] => invert H
    end.
    match goal with
    | [ H : step _ _ |- _ ] => invert H
    end.
    right.
    exists (App x e2).
    eapply StepRule with (C := App1 C e2).
    eauto.
    eauto.
    assumption.
  Qed.

  (* Replacing a typing context with an equal one has no effect (useful to guide
   * proof search as a hint). *)
  Lemma hasty_change : forall G e t,
    hasty G e t
    -> forall G', G' = G
      -> hasty G' e t.
  Proof.
    induct 1; simplify; constructor || econstructor.
    rewrite H0, H; equality.
    rewrite H1. assumption.
    rewrite H1. assumption.
    rewrite H0. assumption.
    rewrite H1. eassumption.
    rewrite H1. eassumption.
  Qed.

  Hint Resolve hasty_change.

  Lemma weakening : forall G e t,
    hasty G e t
    -> forall G', (forall x t, G $? x = Some t -> G' $? x = Some t)
      -> hasty G' e t.
  Proof.
    induct 1; simplify.
    constructor. apply H0, H.
    constructor.
    constructor; apply IHhasty1 || apply IHhasty2; assumption.
    constructor. apply IHhasty. simplify. cases (x ==v x0); simplify; eauto.
    econstructor; apply IHhasty1 || apply IHhasty2; assumption.
  Qed.

  (* Replacing a variable with a properly typed term preserves typing. *)
  Lemma substitution : forall G x t' e t e',
    hasty (G $+ (x, t')) e t
    -> hasty $0 e' t'
    -> hasty G (subst e' x e) t.
  Proof.
    induct 1; simplify.
    - cases (x0 ==v x); simplify.
      * invert H. apply weakening with (G := $0); auto.
      * constructor. assumption.
    - constructor.
    - constructor; (eapply IHhasty1 || eapply IHhasty2); eauto.
    - constructor. cases (x0 ==v x).
      * eapply weakening.
        + eassumption.
        + simplify. rewrite e. cases (x ==v x1); simplify; assumption.
      * eapply IHhasty; eauto.
    - econstructor.
      * eapply IHhasty1; eauto.
      * eapply IHhasty2; eauto.
  Qed.

  Lemma preservation0 : forall e1 e2,
    step0 e1 e2
    -> forall t, hasty $0 e1 t
      -> hasty $0 e2 t.
  Proof.
    invert 1; simplify.
    - invert H.
      invert H4.
      eapply substitution; eassumption.
    - invert H.
      constructor.
  Qed.

  Lemma generalize_plug : forall e1 C e1',
    plug C e1 e1'
    -> forall e2 e2', plug C e2 e2'
      -> (forall t, hasty $0 e1 t -> hasty $0 e2 t)
      -> (forall t, hasty $0 e1' t -> hasty $0 e2' t).
  Proof.
    induct 1; simplify.

    - invert H. auto.
    - invert H0.
      invert H2.
      constructor.
      + eapply IHplug; eassumption.
      + assumption.
    - invert H1.
      invert H3.
      constructor; try assumption.
      + eapply IHplug; eassumption.
    - invert H0.
      invert H2.
      econstructor.
      + eapply IHplug; eassumption.
      + assumption.
    - invert H1.
      invert H3.
      econstructor.
      + eassumption.
      + eapply IHplug; eassumption.
  Qed.

  Lemma preservation : forall e1 e2,
    step e1 e2
    -> forall t, hasty $0 e1 t
      -> hasty $0 e2 t.
  Proof.
    invert 1; simplify.
    eapply generalize_plug with (e1' := e1).
    - eassumption.
    - eassumption.
    - simplify.
      eapply preservation0; eassumption.
    - assumption.
  Qed.

  Theorem safety : forall e t, hasty $0 e t
    -> invariantFor (trsys_of e) unstuck.
  Proof.
    simplify.

    (* Step 1: strengthen the invariant.  In particular, the typing relation is
     * exactly the right stronger invariant!  Our progress theorem proves the
     * required invariant inclusion. *)
    apply invariant_weaken with (invariant1 := fun e' => hasty $0 e' t).

    (* Step 2: apply invariant induction, whose induction step turns out to match
     * our preservation theorem exactly! *)
    apply invariant_induction; simplify.
    equality.

    eapply preservation.
    eassumption.
    assumption.

    simplify.
    eapply progress.
    eassumption.
  Qed.
End Stlc.


Require Import study03.

Module study04.

Theorem double_injective : forall n m,
  double n = double m -> n = m.
Proof.
  induction n. simpl. induction m. reflexivity.
  simpl. intros H. inversion H.
  simpl. induction m. simpl. intros H.
  inversion H. simpl. intros H.
  inversion H. apply IHn in H1.
  rewrite H1. reflexivity.
Qed.

Theorem double_injective_take2 : forall n m,
  double n = double m -> n = m.
Proof.
  intros n m.
  generalize dependent n.
  induction m. simpl. induction n.
  reflexivity. simpl. intros H.
  inversion H. simpl. induction n.
  simpl. intros H. inversion H.
  simpl. intros H. inversion H.
  apply IHm in H1. rewrite H1.
  reflexivity.
Qed.
Theorem plus_n_n_injective_take2 : forall n m,
     n + n = m + m -> n = m.
Proof.
  intros n m.
  generalize dependent n.
  induction m. induction n.
  reflexivity. intros H. inversion H.
  simpl. induction n. intros H.
  inversion H. simpl. intros H.
  inversion H. rewrite plus_comm in H1.
  assert (m+S m=S m+m). apply plus_comm.
  rewrite H0 in H1. simpl in H1.
  inversion H1. apply IHm in H3.
  rewrite H3. reflexivity.
Qed.

Theorem index_after_last: forall (n : nat) (X : Type) (l : ImplicitTest.llist X),
ImplicitTest.llength' l = n -> ImplicitTest.lindex' (S n) l = ImplicitTest.lNone'.
Proof.
  intros n X l.
  generalize dependent n.
  induction l. reflexivity.
  simpl. induction n. intros H.
  inversion H. intros H.
  inversion H. rewrite H1.
  apply IHl. apply H1.
Qed.
Lemma lapp_lcons_lsnoc : forall (X:Type) (l:ImplicitTest.llist X) (v:X),
ImplicitTest.lapp' l (ImplicitTest.lcons' v ImplicitTest.lnil')
  =ImplicitTest.lsnoc' l v.
Proof.
  intros X l v. induction l. reflexivity.
  simpl. rewrite IHl. reflexivity.
Qed.
Theorem length_snoc''' : forall (n : nat) (X : Type)
                              (v : X) (l : ImplicitTest.llist X),
     ImplicitTest.llength' l = n -> ImplicitTest.llength' (ImplicitTest.lsnoc' l v) = S n.
Proof.
  intros n X v l.
  generalize dependent n.
  induction l. simpl.
  induction n. reflexivity.
  intros H. inversion H.
  simpl. induction n.
  intros H. inversion H.
  intros H. inversion H.
  rewrite H1.
  apply ImplicitTest.study03'.eq_remove_S.
  rewrite lapp_lcons_lsnoc.
  apply IHl. apply H1.
Qed.
Notation "x :: y" := (ImplicitTest.lcons' x y) (at level 60, right associativity).
Notation "[ ]" := ImplicitTest.lnil'.
Notation "[ x , .. , y ]" := (ImplicitTest.lcons' x .. (ImplicitTest.lcons' y []) ..).
Notation "x ++ y" := (ImplicitTest.lapp' x y) (at level 60, right associativity).

Theorem app_length_cons : forall (X : Type) (l1 l2 : ImplicitTest.llist X)
                                  (x : X) (n : nat),
     ImplicitTest.llength' (l1 ++ (x :: l2)) = n ->
     S (ImplicitTest.llength' (l1 ++ l2)) = n.
Proof.
  intros X l1 l2 x n.
  generalize dependent n.
  generalize dependent l2.
  induction l1. intros l2 n H.
  rewrite <- H. reflexivity.
  simpl. induction n.
  intros H. inversion H.
  intros H. inversion H.
  apply ImplicitTest.study03'.eq_remove_S.
  rewrite H1. apply IHl1.
  apply H1.
Qed.
Theorem app_length_cons_inv : forall (X : Type) (l1 l2 : ImplicitTest.llist X)
                                  (x : X) (n : nat),
     S (ImplicitTest.llength' (l1 ++ l2)) = n ->
     ImplicitTest.llength' (l1 ++ (x :: l2)) = n.
Proof.
  intros X l1 l2 x n.
  generalize dependent n.
  generalize dependent l2.
  induction l1. intros l2 n H.
  rewrite <- H. reflexivity.
  simpl. induction n.
  intros H. inversion H.
  intros H. inversion H.
  apply ImplicitTest.study03'.eq_remove_S.
  rewrite H1. apply IHl1. apply H1.
Qed.
Theorem app_length_twice : forall (X:Type) (n:nat) (l:ImplicitTest.llist X),
  ImplicitTest.llength' l = n -> ImplicitTest.llength' (l ++ l) = n + n.
Proof.
  intros X n l. generalize dependent n.
  induction l. simpl. intros n H.
  rewrite <- H. reflexivity.
  simpl. induction n.
  intros H. inversion H.
  simpl. intros H. inversion H.
  apply ImplicitTest.study03'.eq_remove_S.
  rewrite H1. rewrite plus_comm. simpl.
  apply app_length_cons_inv.
  apply ImplicitTest.study03'.eq_remove_S.
  apply IHl. apply H1.
Qed.

End study04.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (z : natural) (y : natural) : natural := mult z (plus Zero y).


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (x : natural) (y : natural) : natural := mult y (Succ x).


(* *)
Require Import Arith.
Require Import Omega.
Set Implicit Arguments.

(*
Section BinTree.

Variable A : Set.

Inductive bintree (A : Set) : Set :=
  | Leaf : bintree A
  | Node : bintree A -> nat -> A -> bintree A -> bintree A.
*)

(* Dependent types, a type holds a theorem -> Curry Howard Isomorphism *)
Inductive order (x y : nat) : Set :=
  | LT : x < y -> order x y
  | EQ : x = y -> order x y
  | GT : x > y -> order x y.

Lemma order_correct :
  forall m n,
    order m n -> order (S m) (S n).

  intros.
  destruct H.
  apply LT. omega.
  apply EQ. omega.
  apply GT. omega.
Qed.

Fixpoint  compare (m n : nat) : order m n :=
  match m, n with
    | 0, 0 => EQ eq_refl
    | S m', S n' => order_correct (compare m' n')
    | S _, 0 => GT (gt_Sn_O _)
    | 0, S _ => LT (lt_0_Sn _)
  end.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (lf3 : natural) (z : natural) (lf2 : natural) (lf1 : natural)
  : natural := mult lf1 (Succ Zero).


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (lf1 : natural) (y : natural) (x : natural) (lf2 : natural)
  : natural := plus Zero (Succ y).


(** * MoreCoq: More About Coq *)

Require Export Poly.

(** This chapter introduces several more proof strategies and tactics that,
    together, allow us to prove theorems about the functional
    programs we have been writing. In particular, we'll reason about
    functions that work with natural numbers and lists.

    In particular, we will see:

    - how to use auxiliary lemmas, in both forwards and backwards reasoning
    - how to reason about data constructors, which are injective and disjoint
    - how to create a strong induction hypotheses (and when strengthening is required)
    - how to reason by case analysis
 *)

(* ###################################################### *)
(** * The [apply] Tactic *)

(** We often encounter situations where the goal to be proved is
    exactly the same as some hypothesis in the context or some
    previously proved lemma. *)

Theorem silly1 : forall (n m o p : nat),
     n = m  ->
     [n;o] = [n;p] ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  rewrite <- eq1.
  (* At this point, we could finish with
     "[rewrite -> eq2. reflexivity.]" as we have
     done several times above. But we can achieve the
     same effect in a single step by using the
     [apply] tactic instead: *)
  apply eq2.  Qed.

(** The [apply] tactic also works with _conditional_ hypotheses
    and lemmas: if the statement being applied is an implication, then
    the premises of this implication will be added to the list of
    subgoals needing to be proved. *)

Theorem silly2 : forall (n m o p : nat),
     n = m  ->
     (forall (q r : nat), q = r -> [q;o] = [r;p]) ->
     [n;o] = [m;p].
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** You may find it instructive to experiment with this proof
    and see if there is a way to complete it using just [rewrite]
    instead of [apply]. *)

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] binding some _universal variables_.  When
    Coq matches the current goal against the conclusion of [H], it
    will try to find appropriate values for these variables.  For
    example, when we do [apply eq2] in the following proof, the
    universal variable [q] in [eq2] gets instantiated with [n] and [r]
    gets instantiated with [m]. *)

Theorem silly2a : forall (n m : nat),
     (n,n) = (m,m)  ->
     (forall (q r : nat), (q,q) = (r,r) -> [q] = [r]) ->
     [n] = [m].
Proof.
  intros n m eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** **** Exercise: 2 stars, optional (silly_ex)  *)
(** Complete the following proof without using [simpl]. *)

Theorem silly_ex :
     (forall n, evenb n = true -> oddb (S n) = true) ->
     evenb 3 = true ->
     oddb 4 = true.
Proof.
  intros H H1. apply H1. Qed.
(** [] *)

(** To use the [apply] tactic, the (conclusion of the) fact
    being applied must match the goal _exactly_ -- for example, [apply]
    will not work if the left and right sides of the equality are
    swapped. *)

Theorem silly3_firsttry : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  simpl.
  (* Here we cannot use [apply] directly *)
Abort.

(** In this case we can use the [symmetry] tactic, which switches the
    left and right sides of an equality in the goal. *)

Theorem silly3 : forall (n : nat),
     true = beq_nat n 5  ->
     beq_nat (S (S n)) 7 = true.
Proof.
  intros n H.
  symmetry.
  simpl. (* Actually, this [simpl] is unnecessary, since
            [apply] will perform simplification first. *)
  apply H.  Qed.

(** **** Exercise: 3 stars (apply_exercise1)  *)
(** Hint: you can use [apply] with previously defined lemmas, not
    just hypotheses in the context.  Remember that [SearchAbout] is
    your friend. *)

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 1 star, optional (apply_rewrite)  *)
(** Briefly explain the difference between the tactics [apply] and
    [rewrite].  Are there situations where both can usefully be
    applied?
  (* FILL IN HERE *)
*)
(** [] *)

(* ###################################################### *)
(** * The [apply ... with ...] Tactic *)

(** The following silly example uses two rewrites in a row to
    get from [[a,b]] to [[e,f]]. *)

Example trans_eq_example : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  rewrite -> eq1. rewrite -> eq2. reflexivity.  Qed.

(** Since this is a common pattern, we might
    abstract it out as a lemma recording once and for all
    the fact that equality is transitive. *)

Theorem trans_eq : forall (X:Type) (n m o : X),
  n = m -> m = o -> n = o.
Proof.
  intros X n m o eq1 eq2. rewrite -> eq1. rewrite -> eq2.
  reflexivity.  Qed.

(** Now, we should be able to use [trans_eq] to
    prove the above example.  However, to do this we need
    a slight refinement of the [apply] tactic. *)

Example trans_eq_example' : forall (a b c d e f : nat),
     [a;b] = [c;d] ->
     [c;d] = [e;f] ->
     [a;b] = [e;f].
Proof.
  intros a b c d e f eq1 eq2.
  (* If we simply tell Coq [apply trans_eq] at this point,
     it can tell (by matching the goal against the
     conclusion of the lemma) that it should instantiate [X]
     with [[nat]], [n] with [[a,b]], and [o] with [[e,f]].
     However, the matching process doesn't determine an
     instantiation for [m]: we have to supply one explicitly
     by adding [with (m:=[c,d])] to the invocation of
     [apply]. *)
  apply trans_eq with (m:=[c;d]). apply eq1. apply eq2.   Qed.

(**  Actually, we usually don't have to include the name [m]
    in the [with] clause; Coq is often smart enough to
    figure out which instantiation we're giving. We could
    instead write: [apply trans_eq with [c,d]]. *)

(** **** Exercise: 3 stars, optional (apply_with_exercise)  *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################### *)
(** * The [inversion] tactic *)

(** Recall the definition of natural numbers:
     Inductive nat : Type :=
       | O : nat
       | S : nat -> nat.
    It is clear from this definition that every number has one of two
    forms: either it is the constructor [O] or it is built by applying
    the constructor [S] to another number.  But there is more here than
    meets the eye: implicit in the definition (and in our informal
    understanding of how datatype declarations work in other
    programming languages) are two other facts:

    - The constructor [S] is _injective_.  That is, the only way we can
      have [S n = S m] is if [n = m].

    - The constructors [O] and [S] are _disjoint_.  That is, [O] is not
      equal to [S n] for any [n]. *)

(** Similar principles apply to all inductively defined types: all
    constructors are injective, and the values built from distinct
    constructors are never equal.  For lists, the [cons] constructor is
    injective and [nil] is different from every non-empty list.  For
    booleans, [true] and [false] are unequal.  (Since neither [true]
    nor [false] take any arguments, their injectivity is not an issue.) *)

(** Coq provides a tactic called [inversion] that allows us to exploit
    these principles in proofs.

    The [inversion] tactic is used like this.  Suppose [H] is a
    hypothesis in the context (or a previously proven lemma) of the
    form
      c a1 a2 ... an = d b1 b2 ... bm
    for some constructors [c] and [d] and arguments [a1 ... an] and
    [b1 ... bm].  Then [inversion H] instructs Coq to "invert" this
    equality to extract the information it contains about these terms:

    - If [c] and [d] are the same constructor, then we know, by the
      injectivity of this constructor, that [a1 = b1], [a2 = b2],
      etc.; [inversion H] adds these facts to the context, and tries
      to use them to rewrite the goal.

    - If [c] and [d] are different constructors, then the hypothesis
      [H] is contradictory.  That is, a false assumption has crept
      into the context, and this means that any goal whatsoever is
      provable!  In this case, [inversion H] marks the current goal as
      completed and pops it off the goal stack. *)

(** The [inversion] tactic is probably easier to understand by
    seeing it in action than from general descriptions like the above.
    Below you will find example theorems that demonstrate the use of
    [inversion] and exercises to test your understanding. *)

Theorem eq_add_S : forall (n m : nat),
     S n = S m ->
     n = m.
Proof.
  intros n m eq. inversion eq. reflexivity.  Qed.

Theorem silly4 : forall (n m : nat),
     [n] = [m] ->
     n = m.
Proof.
  intros n o eq. inversion eq. reflexivity.  Qed.

(** As a convenience, the [inversion] tactic can also
    destruct equalities between complex values, binding
    multiple variables as it goes. *)

Theorem silly5 : forall (n m o : nat),
     [n;m] = [o;o] ->
     [n] = [m].
Proof.
  intros n m o eq. inversion eq. reflexivity. Qed.

(** **** Exercise: 1 star (sillyex1)  *)
Example sillyex1 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = z :: j ->
     y :: l = x :: j ->
     x = y.
Proof.
  intros X x y z l j H1 H2. inversion H1. inversion H2. rewrite H0. reflexivity. Qed.
(** [] *)

Theorem silly6 : forall (n : nat),
     S n = O ->
     2 + 2 = 5.
Proof.
  intros n contra. inversion contra. Qed.

Theorem silly7 : forall (n m : nat),
     false = true ->
     [n] = [m].
Proof.
  intros n m contra. inversion contra.  Qed.

(** **** Exercise: 1 star (sillyex2)  *)
Example sillyex2 : forall (X : Type) (x y z : X) (l j : list X),
     x :: y :: l = [] ->
     y :: l = z :: j ->
     x = z.
Proof.
  intros X x y z l j H1 H2. inversion H1. Qed.
(** [] *)

(** While the injectivity of constructors allows us to reason
    [forall (n m : nat), S n = S m -> n = m], the reverse direction of
    the implication is an instance of a more general fact about
    constructors and functions, which we will often find useful: *)

Theorem f_equal : forall (A B : Type) (f: A -> B) (x y: A),
    x = y -> f x = f y.
Proof. intros A B f x y eq. rewrite eq.  reflexivity.  Qed.

(** **** Exercise: 2 stars, optional (practice)  *)
(** A couple more nontrivial but not-too-complicated proofs to work
    together in class, or for you to work as exercises. *)

Theorem beq_nat_0_l : forall n,
   beq_nat 0 n = true -> n = 0.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem beq_nat_0_r : forall n,
   beq_nat n 0 = true -> n = 0.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################### *)
(** * Using Tactics on Hypotheses *)

(** By default, most tactics work on the goal formula and leave
    the context unchanged.  However, most tactics also have a variant
    that performs a similar operation on a statement in the context.

    For example, the tactic [simpl in H] performs simplification in
    the hypothesis named [H] in the context. *)

Theorem S_inj : forall (n m : nat) (b : bool),
     beq_nat (S n) (S m) = b  ->
     beq_nat n m = b.
Proof.
  intros n m b H. simpl in H. apply H.  Qed.

(** Similarly, the tactic [apply L in H] matches some
    conditional statement [L] (of the form [L1 -> L2], say) against a
    hypothesis [H] in the context.  However, unlike ordinary
    [apply] (which rewrites a goal matching [L2] into a subgoal [L1]),
    [apply L in H] matches [H] against [L1] and, if successful,
    replaces it with [L2].

    In other words, [apply L in H] gives us a form of "forward
    reasoning" -- from [L1 -> L2] and a hypothesis matching [L1], it
    gives us a hypothesis matching [L2].  By contrast, [apply L] is
    "backward reasoning" -- it says that if we know [L1->L2] and we
    are trying to prove [L2], it suffices to prove [L1].

    Here is a variant of a proof from above, using forward reasoning
    throughout instead of backward reasoning. *)

Theorem silly3' : forall (n : nat),
  (beq_nat n 5 = true -> beq_nat (S (S n)) 7 = true) ->
     true = beq_nat n 5  ->
     true = beq_nat (S (S n)) 7.
Proof.
  intros n eq H.
  symmetry in H. apply eq in H. symmetry in H.
  apply H.  Qed.

(** Forward reasoning starts from what is _given_ (premises,
    previously proven theorems) and iteratively draws conclusions from
    them until the goal is reached.  Backward reasoning starts from
    the _goal_, and iteratively reasons about what would imply the
    goal, until premises or previously proven theorems are reached.
    If you've seen informal proofs before (for example, in a math or
    computer science class), they probably used forward reasoning.  In
    general, Coq tends to favor backward reasoning, but in some
    situations the forward style can be easier to use or to think
    about.  *)

(** **** Exercise: 3 stars (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise. *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    destruct m as [| m'].
    reflexivity. intros. inversion H.
  Case "n = S n'".
    destruct m as [| m'].
    simpl. intros. inversion H.
    simpl. rewrite <- plus_n_Sm. rewrite<- plus_n_Sm.
    intros. apply f_equal. apply IHn'. inversion H. reflexivity. Qed.
(** [] *)

(* ###################################################### *)
(** * Varying the Induction Hypothesis *)

(** Sometimes it is important to control the exact form of the
    induction hypothesis when carrying out inductive proofs in Coq.
    In particular, we need to be careful about which of the
    assumptions we move (using [intros]) from the goal to the context
    before invoking the [induction] tactic.  For example, suppose
    we want to show that the [double] function is injective -- i.e.,
    that it always maps different arguments to different results:
    Theorem double_injective: forall n m, double n = double m -> n = m.
    The way we _start_ this proof is a little bit delicate: if we
    begin it with
      intros n. induction n.
]]
    all is well.  But if we begin it with
      intros n m. induction n.
    we get stuck in the middle of the inductive case... *)

Theorem double_injective_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction n as [| n'].
  Case "n = O". simpl. intros eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "n = S n'". intros eq. destruct m as [| m'].
    SCase "m = O". inversion eq.
    SCase "m = S m'".  apply f_equal.
      (* Here we are stuck.  The induction hypothesis, [IHn'], does
         not give us [n' = m'] -- there is an extra [S] in the
         way -- so the goal is not provable. *)
      Abort.

(** What went wrong? *)

(** The problem is that, at the point we invoke the induction
    hypothesis, we have already introduced [m] into the context --
    intuitively, we have told Coq, "Let's consider some particular
    [n] and [m]..." and we now have to prove that, if [double n =
    double m] for _this particular_ [n] and [m], then [n = m].

    The next tactic, [induction n] says to Coq: We are going to show
    the goal by induction on [n].  That is, we are going to prove that
    the proposition

      - [P n]  =  "if [double n = double m], then [n = m]"

    holds for all [n] by showing

      - [P O]

         (i.e., "if [double O = double m] then [O = m]")

      - [P n -> P (S n)]

        (i.e., "if [double n = double m] then [n = m]" implies "if
        [double (S n) = double m] then [S n = m]").

    If we look closely at the second statement, it is saying something
    rather strange: it says that, for a _particular_ [m], if we know

      - "if [double n = double m] then [n = m]"

    then we can prove

       - "if [double (S n) = double m] then [S n = m]".

    To see why this is strange, let's think of a particular [m] --
    say, [5].  The statement is then saying that, if we know

      - [Q] = "if [double n = 10] then [n = 5]"

    then we can prove

      - [R] = "if [double (S n) = 10] then [S n = 5]".

    But knowing [Q] doesn't give us any help with proving [R]!  (If we
    tried to prove [R] from [Q], we would say something like "Suppose
    [double (S n) = 10]..." but then we'd be stuck: knowing that
    [double (S n)] is [10] tells us nothing about whether [double n]
    is [10], so [Q] is useless at this point.) *)

(** To summarize: Trying to carry out this proof by induction on [n]
    when [m] is already in the context doesn't work because we are
    trying to prove a relation involving _every_ [n] but just a
    _single_ [m]. *)

(** The good proof of [double_injective] leaves [m] in the goal
    statement at the point where the [induction] tactic is invoked on
    [n]: *)

Theorem double_injective : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
  Case "n = O". simpl. intros m eq. destruct m as [| m'].
    SCase "m = O". reflexivity.
    SCase "m = S m'". inversion eq.
  Case "n = S n'".
    (* Notice that both the goal and the induction
       hypothesis have changed: the goal asks us to prove
       something more general (i.e., to prove the
       statement for _every_ [m]), but the IH is
       correspondingly more flexible, allowing us to
       choose any [m] we like when we apply the IH.  *)
    intros m eq.
    (* Now we choose a particular [m] and introduce the
       assumption that [double n = double m].  Since we
       are doing a case analysis on [n], we need a case
       analysis on [m] to keep the two "in sync." *)
    destruct m as [| m'].
    SCase "m = O".
      (* The 0 case is trivial *)
      inversion eq.
    SCase "m = S m'".
      apply f_equal.
      (* At this point, since we are in the second
         branch of the [destruct m], the [m'] mentioned
         in the context at this point is actually the
         predecessor of the one we started out talking
         about.  Since we are also in the [S] branch of
         the induction, this is perfect: if we
         instantiate the generic [m] in the IH with the
         [m'] that we are talking about right now (this
         instantiation is performed automatically by
         [apply]), then [IHn'] gives us exactly what we
         need to finish the proof. *)
      apply IHn'. inversion eq. reflexivity. Qed.

(** What this teaches us is that we need to be careful about using
    induction to try to prove something too specific: If we're proving
    a property of [n] and [m] by induction on [n], we may need to
    leave [m] generic. *)

(** The proof of this theorem (left as an exercise) has to be treated similarly: *)

(** **** Exercise: 2 stars (beq_nat_true)  *)
Theorem beq_nat_true : forall n m,
    beq_nat n m = true -> n = m.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    intros. destruct m as [| m'].
    reflexivity.
    simpl in H. inversion H.
  Case "n = S n'".
    intros. destruct m as [| m'].
    simpl in H. inversion H.
    simpl in H. apply f_equal. apply IHn'. apply H. Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (beq_nat_true_informal)  *)
(** Give a careful informal proof of [beq_nat_true], being as explicit
    as possible about quantifiers. *)

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

(** The strategy of doing fewer [intros] before an [induction] doesn't
    always work directly; sometimes a little _rearrangement_ of
    quantified variables is needed.  Suppose, for example, that we
    wanted to prove [double_injective] by induction on [m] instead of
    [n]. *)

Theorem double_injective_take2_FAILED : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m. induction m as [| m'].
  Case "m = O". simpl. intros eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "n = S n'".  apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (If we simply say [induction m] without
    introducing anything first, Coq will automatically introduce
    [n] for us!)   *)

(** What can we do about this?  One possibility is to rewrite the
    statement of the lemma so that [m] is quantified before [n].  This
    will work, but it's not nice: We don't want to have to mangle the
    statements of lemmas to fit the needs of a particular strategy for
    proving them -- we want to state them in the most clear and
    natural way. *)

(**  What we can do instead is to first introduce all the
    quantified variables and then _re-generalize_ one or more of
    them, taking them out of the context and putting them back at
    the beginning of the goal.  The [generalize dependent] tactic
    does this. *)

Theorem double_injective_take2 : forall n m,
     double n = double m ->
     n = m.
Proof.
  intros n m.
  (* [n] and [m] are both in the context *)
  generalize dependent n.
  (* Now [n] is back in the goal and we can do induction on
     [m] and get a sufficiently general IH. *)
  induction m as [| m'].
  Case "m = O". simpl. intros n eq. destruct n as [| n'].
    SCase "n = O". reflexivity.
    SCase "n = S n'". inversion eq.
  Case "m = S m'". intros n eq. destruct n as [| n'].
    SCase "n = O". inversion eq.
    SCase "n = S n'". apply f_equal.
      apply IHm'. inversion eq. reflexivity. Qed.

(** Let's look at an informal proof of this theorem.  Note that
    the proposition we prove by induction leaves [n] quantified,
    corresponding to the use of generalize dependent in our formal
    proof.

_Theorem_: For any nats [n] and [m], if [double n = double m], then
  [n = m].

_Proof_: Let [m] be a [nat]. We prove by induction on [m] that, for
  any [n], if [double n = double m] then [n = m].

  - First, suppose [m = 0], and suppose [n] is a number such
    that [double n = double m].  We must show that [n = 0].

    Since [m = 0], by the definition of [double] we have [double n =
    0].  There are two cases to consider for [n].  If [n = 0] we are
    done, since this is what we wanted to show.  Otherwise, if [n = S
    n'] for some [n'], we derive a contradiction: by the definition of
    [double] we would have [double n = S (S (double n'))], but this
    contradicts the assumption that [double n = 0].

  - Otherwise, suppose [m = S m'] and that [n] is again a number such
    that [double n = double m].  We must show that [n = S m'], with
    the induction hypothesis that for every number [s], if [double s =
    double m'] then [s = m'].

    By the fact that [m = S m'] and the definition of [double], we
    have [double n = S (S (double m'))].  There are two cases to
    consider for [n].

    If [n = 0], then by definition [double n = 0], a contradiction.
    Thus, we may assume that [n = S n'] for some [n'], and again by
    the definition of [double] we have [S (S (double n')) = S (S
    (double m'))], which implies by inversion that [double n' = double
    m'].

    Instantiating the induction hypothesis with [n'] thus allows us to
    conclude that [n' = m'], and it follows immediately that [S n' = S
    m'].  Since [S n' = n] and [S m' = m], this is just what we wanted
    to show. [] *)

(** Here's another illustration of [inversion] and using an
    appropriately general induction hypothesis.  This is a slightly
    roundabout way of stating a fact that we have already proved
    above.  The extra equalities force us to do a little more
    equational reasoning and exercise some of the tactics we've seen
    recently. *)

Theorem length_snoc' : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l. induction l as [| v' l'].

  Case "l = []".
    intros n eq. rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    intros n eq. simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "n = S n'".
      apply f_equal. apply IHl'. inversion eq. reflexivity. Qed.

(** It might be tempting to start proving the above theorem
    by introducing [n] and [eq] at the outset.  However, this leads
    to an induction hypothesis that is not strong enough.  Compare
    the above to the following (aborted) attempt: *)

Theorem length_snoc_bad : forall (X : Type) (v : X)
                              (l : list X) (n : nat),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  intros X v l n eq. induction l as [| v' l'].

  Case "l = []".
    rewrite <- eq. reflexivity.

  Case "l = v' :: l'".
    simpl. destruct n as [| n'].
    SCase "n = 0". inversion eq.
    SCase "n = S n'".
      apply f_equal. Abort. (* apply IHl'. *) (* The IH doesn't apply! *)

(** As in the double examples, the problem is that by
    introducing [n] before doing induction on [l], the induction
    hypothesis is specialized to one particular natural number, namely
    [n].  In the induction case, however, we need to be able to use
    the induction hypothesis on some other natural number [n'].
    Retaining the more general form of the induction hypothesis thus
    gives us more flexibility.

    In general, a good rule of thumb is to make the induction hypothesis
    as general as possible. *)

(** **** Exercise: 3 stars (gen_dep_practice)  *)
(** Prove this by induction on [l]. *)

Theorem index_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     index n l = None.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (index_after_last_informal)  *)
(** Write an informal proof corresponding to your Coq proof
    of [index_after_last]:

     _Theorem_: For all sets [X], lists [l : list X], and numbers
      [n], if [length l = n] then [index n l = None].

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

(** **** Exercise: 3 stars, optional (gen_dep_practice_more)  *)
(** Prove this by induction on [l]. *)

Theorem length_snoc''' : forall (n : nat) (X : Type)
                              (v : X) (l : list X),
     length l = n ->
     length (snoc l v) = S n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (app_length_cons)  *)
(** Prove this by induction on [l1], without using [app_length]
    from [Lists]. *)

Theorem app_length_cons : forall (X : Type) (l1 l2 : list X)
                                  (x : X) (n : nat),
     length (l1 ++ (x :: l2)) = n ->
     S (length (l1 ++ l2)) = n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, optional (app_length_twice)  *)
(** Prove this by induction on [l], without using app_length. *)

Theorem app_length_twice : forall (X:Type) (n:nat) (l:list X),
     length l = n ->
     length (l ++ l) = n + n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (double_induction)  *)
(** Prove the following principle of induction over two naturals. *)

Theorem double_induction: forall (P : nat -> nat -> Prop),
  P 0 0 ->
  (forall m, P m 0 -> P (S m) 0) ->
  (forall n, P 0 n -> P 0 (S n)) ->
  (forall m n, P m n -> P (S m) (S n)) ->
  forall m n, P m n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ###################################################### *)
(** * Using [destruct] on Compound Expressions *)

(** We have seen many examples where the [destruct] tactic is
    used to perform case analysis of the value of some variable.  But
    sometimes we need to reason by cases on the result of some
    _expression_.  We can also do this with [destruct].

    Here are some examples: *)

Definition sillyfun (n : nat) : bool :=
  if beq_nat n 3 then false
  else if beq_nat n 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (beq_nat n 3).
    Case "beq_nat n 3 = true". reflexivity.
    Case "beq_nat n 3 = false". destruct (beq_nat n 5).
      SCase "beq_nat n 5 = true". reflexivity.
      SCase "beq_nat n 5 = false". reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (beq_nat n 3) then ... else ...].  Well,
    either [n] is equal to [3] or it isn't, so we use [destruct
    (beq_nat n 3)] to let us reason about the two cases.

    In general, the [destruct] tactic can be used to perform case
    analysis of the results of arbitrary computations.  If [e] is an
    expression whose type is some inductively defined type [T], then,
    for each constructor [c] of [T], [destruct e] generates a subgoal
    in which all occurrences of [e] (in the goal and in the context)
    are replaced by [c].

*)

(** **** Exercise: 1 star (override_shadow)  *)
Theorem override_shadow : forall (X:Type) x1 x2 k1 k2 (f : nat->X),
  (override (override f k1 x2) k1 x1) k2 = (override f k1 x1) k2.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, optional (combine_split)  *)
(** Complete the proof below *)

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** Sometimes, doing a [destruct] on a compound expression (a
    non-variable) will erase information we need to complete a proof. *)
(** For example, suppose
    we define a function [sillyfun1] like this: *)

Definition sillyfun1 (n : nat) : bool :=
  if beq_nat n 3 then true
  else if beq_nat n 5 then true
  else false.

(** And suppose that we want to convince Coq of the rather
    obvious observation that [sillyfun1 n] yields [true] only when [n]
    is odd.  By analogy with the proofs we did with [sillyfun] above,
    it is natural to start the proof like this: *)

Theorem sillyfun1_odd_FAILED : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3).
  (* stuck... *)
Abort.

(** We get stuck at this point because the context does not
    contain enough information to prove the goal!  The problem is that
    the substitution peformed by [destruct] is too brutal -- it threw
    away every occurrence of [beq_nat n 3], but we need to keep some
    memory of this expression and how it was destructed, because we
    need to be able to reason that since, in this branch of the case
    analysis, [beq_nat n 3 = true], it must be that [n = 3], from
    which it follows that [n] is odd.

    What we would really like is to substitute away all existing
    occurences of [beq_nat n 3], but at the same time add an equation
    to the context that records which case we are in.  The [eqn:]
    qualifier allows us to introduce such an equation (with whatever
    name we choose). *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (beq_nat n 3) eqn:Heqe3.
  (* Now we have the same state as at the point where we got stuck
    above, except that the context contains an extra equality
    assumption, which is exactly what we need to make progress. *)
    Case "e3 = true". apply beq_nat_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    Case "e3 = false".
     (* When we come to the second equality test in the body of the
       function we are reasoning about, we can use [eqn:] again in the
       same way, allow us to finish the proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        SCase "e5 = true".
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        SCase "e5 = false". inversion eq.  Qed.

(** **** Exercise: 2 stars (destruct_eqn_practice)  *)
Theorem bool_fn_applied_thrice :
  forall (f : bool -> bool) (b : bool),
  f (f (f b)) = f b.
Proof.
  intros f b. destruct b.
    Case "b = true".
      destruct (f true) eqn:Ha.
        rewrite -> Ha. apply Ha.
      destruct (f false) eqn:Hb.
        rewrite -> Ha. reflexivity.
        rewrite -> Hb. reflexivity.
    Case "b = false".
      destruct (f false) eqn:Hc.
        destruct (f true) eqn:Hd.
          rewrite -> Hd. reflexivity.
          rewrite -> Hc. reflexivity.
        rewrite -> Hc. rewrite -> Hc. reflexivity.
  Qed.
(** [] *)

(** **** Exercise: 2 stars (override_same)  *)
Theorem override_same : forall (X:Type) x1 k1 k2 (f : nat->X),
  f k1 = x1 ->
  (override f k1 x1) k2 = f k2.
Proof.
  intros X x1 k1 k2 f Hx1.
  unfold override.
  destruct (beq_nat k1 k2) eqn:Hk1k2.
  Case "k1 = k2".
    apply beq_nat_true in Hk1k2.
    rewrite <- Hx1.
    rewrite -> Hk1k2. reflexivity.
  Case "k1 != k2".
    reflexivity. Qed.
(** [] *)

(* ################################################################## *)
(** * Review *)

(** We've now seen a bunch of Coq's fundamental tactics.  We'll
    introduce a few more as we go along through the coming lectures,
    and later in the course we'll introduce some more powerful
    _automation_ tactics that make Coq do more of the low-level work
    in many cases.  But basically we've got what we need to get work
    done.

    Here are the ones we've seen:

      - [intros]:
        move hypotheses/variables from goal to context

      - [reflexivity]:
        finish the proof (when the goal looks like [e = e])

      - [apply]:
        prove goal using a hypothesis, lemma, or constructor

      - [apply... in H]:
        apply a hypothesis, lemma, or constructor to a hypothesis in
        the context (forward reasoning)

      - [apply... with...]:
        explicitly specify values for variables that cannot be
        determined by pattern matching

      - [simpl]:
        simplify computations in the goal

      - [simpl in H]:
        ... or a hypothesis

      - [rewrite]:
        use an equality hypothesis (or lemma) to rewrite the goal

      - [rewrite ... in H]:
        ... or a hypothesis

      - [symmetry]:
        changes a goal of the form [t=u] into [u=t]

      - [symmetry in H]:
        changes a hypothesis of the form [t=u] into [u=t]

      - [unfold]:
        replace a defined constant by its right-hand side in the goal

      - [unfold... in H]:
        ... or a hypothesis

      - [destruct... as...]:
        case analysis on values of inductively defined types

      - [destruct... eqn:...]:
        specify the name of an equation to be added to the context,
        recording the result of the case analysis

      - [induction... as...]:
        induction on values of inductively defined types

      - [inversion]:
        reason by injectivity and distinctness of constructors

      - [assert (e) as H]:
        introduce a "local lemma" [e] and call it [H]

      - [generalize dependent x]:
        move the variable [x] (and anything else that depends on it)
        from the context back to an explicit hypothesis in the goal
        formula
*)

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

(** **** Exercise: 3 stars (beq_nat_sym)  *)
Theorem beq_nat_sym : forall (n m : nat),
  beq_nat n m = beq_nat m n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced, optional (beq_nat_sym_informal)  *)
(** Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [beq_nat n m = beq_nat m n].

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

(** **** Exercise: 3 stars, optional (beq_nat_trans)  *)
Theorem beq_nat_trans : forall n m p,
  beq_nat n m = true ->
  beq_nat m p = true ->
  beq_nat n p = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)  *)
(** We have just proven that for all lists of pairs, [combine] is the
    inverse of [split].  How would you formalize the statement that
    [split] is the inverse of [combine]? When is this property true?

    Complete the definition of [split_combine_statement] below with a
    property that states that [split] is the inverse of
    [combine]. Then, prove that the property holds. (Be sure to leave
    your induction hypothesis general by not doing [intros] on more
    things than necessary.  Hint: what property do you need of [l1]
    and [l2] for [split] [combine l1 l2 = (l1,l2)] to be true?)  *)

Definition split_combine_statement : Prop :=
(* FILL IN HERE *) admit.

Theorem split_combine : split_combine_statement.
Proof.
(* FILL IN HERE *) Admitted.

(** [] *)

(** **** Exercise: 3 stars (override_permute)  *)
Theorem override_permute : forall (X:Type) x1 x2 k1 k2 k3 (f : nat->X),
  beq_nat k2 k1 = false ->
  (override (override f k2 x2) k1 x1) k3 = (override (override f k1 x1) k2 x2) k3.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars, advanced (filter_exercise)  *)
(** This one is a bit challenging.  Pay attention to the form of your IH. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced (forall_exists_challenge)  *)
(** Define two recursive [Fixpoints], [forallb] and [existsb].  The
    first checks whether every element in a list satisfies a given
    predicate:
      forallb oddb [1;3;5;7;9] = true

      forallb negb [false;false] = true

      forallb evenb [0;2;4;5] = false

      forallb (beq_nat 5) [] = true
    The second checks whether there exists an element in the list that
    satisfies a given predicate:
      existsb (beq_nat 5) [0;2;3;6] = false

      existsb (andb true) [true;true;false] = true

      existsb oddb [1;0;0;0;0;3] = true

      existsb evenb [] = false
    Next, define a _nonrecursive_ version of [existsb] -- call it
    [existsb'] -- using [forallb] and [negb].

    Prove that [existsb'] and [existsb] have the same behavior.
*)

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

(* $Date: 2014-10-02 08:04:07 +0900 (2014年10月02日 (木)) $ *)


(* Exercise 16 *)

Require Import BenB.

Variables A B C D : Prop.

(* Tertium non datur inverted *)

Theorem exercise_016 : ~A \/ A.
Proof.
neg_e' (~A) first.
neg_i (~A \/ A) second.
hyp first.
dis_i1.
hyp second.
neg_i (~A \/ A) second.
hyp first.
dis_i2.
hyp second.
(* It says 'benbcl_proof' instead of 'benb_proof' because
   you are not allowed to use LEM in this proof. *)
Qed.


Require Export Basics.

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

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


Require Import Omega Program.Basics.

(* ***** UNARY  ***** *)

(* Countdown worker function *)
Fixpoint cdn_wkr (f : nat -> nat) (a n k : nat) : nat :=
  match k with
  | 0    => 0
  | S k' => if (n <=? a) then 0 else
              S (cdn_wkr f a (f n) k')
  end.

(* Countdown *)
Definition countdown_to f a n := cdn_wkr f a n n.

(* Two parameters Inverse Ackerman worker function *)
Fixpoint two_params_inv_ack_wkr (f : nat -> nat) (n k b : nat) : nat :=
  match b with
  | 0    => 0
  | S b' => if (n <=? k) then 0
              else let g := (countdown_to f 1) in
                   S (two_params_inv_ack_wkr (compose g f) (g n) k b')
  end.

(* Two parameters Inverse Ackermann function *)
Definition two_params_inv_ack (m n : nat) : nat :=
  let f := (fun x => x - 2) in
    let n' := (Nat.log2_up n) in
      1 + two_params_inv_ack_wkr f (f n') (m / n) n'.

(* Inverse Ackermann worker function *)
Fixpoint inv_ack_wkr (f : nat -> nat) (n k b : nat) : nat :=
  match b with
  | 0      => k
  | S b' => if (n <=? k) then k
              else let g := (countdown_to f 1) in
                   inv_ack_wkr (compose g f) (g n) (S k) b'
  end.

(* Inverse Ackermann function *)
(* Definition by hard-coding up to the second bin_alpha level, runtime O(n) *)
Definition inv_ack_linear n :=
  match n with
  | 0 | 1 => 0
  | _     => let f := (fun x => x - 2) in inv_ack_wkr f (f n) 1 (n - 1)
  end.

(* ***** BINARY ***** *)

Open Scope N_scope.

(* Supporting function - Use to compute the budget for bin_cdn_wkr and inv_ack_wrk
   Returns length of the binary representation in type "nat" *)
Definition nat_size (n : N) : nat :=
  match n with
  | 0 => 0%nat
  | Npos p => let fix nat_pos_size (x : positive) : nat :=
                  match x with
                  | xH => 1%nat
                  | xI y | xO y => S (nat_pos_size y) end
                  in nat_pos_size p
  end.

(* Countdown worker function *)
Fixpoint bin_cdn_wkr (f : N -> N) (a n : N) (b : nat) : N :=
  match b with
  | O    => 0
  | S b' => if (n <=? a) then 0
             else 1 + bin_cdn_wkr f a (f n) b'
  end.

(* Countdown *)
Definition bin_countdown_to (f : N -> N) (a n : N) : N :=
  bin_cdn_wkr f a n (nat_size (n - a)).

(* Two parameters Binary Inverse Ackerman worker function *)
Fixpoint two_params_bin_inv_ack_wkr (f : N -> N) (n k : N) (b : nat) : N :=
  match b with
  | 0%nat => 0
  | S b'  => if (n <=? k) then 0
              else let g := (bin_countdown_to f 1) in
                   N.succ (two_params_bin_inv_ack_wkr (compose g f) (g n) k b')
  end.

(* Two parameters Binary Inverse Ackermann function *)
Definition two_params_bin_inv_ack (m n : N) : N :=
  let n' := (N.log2_up n) in
    let m' := m / n in
      if (n' - 2 <=? m') then 1
        else if (N.div2 (n' - 2) <=? m') then 2
          else let f := (fun x => N.log2 (x + 2) - 2) in
            3 + two_params_bin_inv_ack_wkr f (f n') m' (nat_size n).

(* Inverse Ackermann worker function *)
Fixpoint bin_inv_ack_wkr (f : N -> N) (n k : N) (b : nat) : N :=
  match b with
  | 0%nat  => k
  | S b' =>
    if n <=? k then k
      else let g := (bin_countdown_to f 1) in
      bin_inv_ack_wkr (compose g f) (g n) (N.succ k) b'
  end.

(* Inverse Ackermann function.
 * Definition by hard-coding up to the fourth bin_alpha level,
 * runtime O(log n) up to the magnitude of n
 * equivalent to O(b) where b = bitsize of n
 *)
Definition bin_inv_ack n :=
  if (n <=? 1) then 0
  else if (n <=? 3) then 1
  else if (n <=? 7) then 2
  else let f := (fun x => N.log2 (x + 2) - 2) in
       bin_inv_ack_wkr f (f n) 3 (nat_size n).

Close Scope N_scope.

(* Please see inv_ack_test.v for a brief demonstration of the time bounds. *)


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (x : natural) (y : natural) (lf1 : natural) : natural :=
  plus y (Succ Zero).


Require Import Coq.ZArith.ZArith.
Require Import Coq.micromega.Lia.
Require Import Coq.Classes.Morphisms.
Require Import Crypto.Util.ZUtil.
Require Import Crypto.Util.Tactics.DestructHead.
Require Import Crypto.Util.Tactics.SpecializeBy.

Local Open Scope Z_scope.

Local Notation stabilizes_after x l := (exists b, forall n, l < n -> Z.testbit x n = b).

Lemma stabilizes_after_Proper x
  : Proper (Z.le ==> Basics.impl) (fun l => stabilizes_after x l).
Proof.
  intros ?? H [b H']; exists b.
  intros n H''; apply (H' n); omega.
Qed.

Lemma stabilization_time (x:Z) : stabilizes_after x (Z.max (Z.log2 (Z.pred (- x))) (Z.log2 x)).
Proof.
  destruct (Z_lt_le_dec x 0); eexists; intros;
    [ eapply Z.bits_above_log2_neg | eapply Z.bits_above_log2]; lia.
Qed.

Lemma stabilization_time_weaker (x:Z) : stabilizes_after x (Z.log2_up (Z.abs x)).
Proof.
  eapply stabilizes_after_Proper; try apply stabilization_time.
  repeat match goal with
         | [ |- context[Z.abs _ ] ] => apply Zabs_ind; intro
         | [ |- context[Z.log2 ?x] ]
           => rewrite (Z.log2_nonpos x) by omega
         | [ |- context[Z.log2_up ?x] ]
           => rewrite (Z.log2_up_nonpos x) by omega
         | _ => rewrite Z.max_r by auto with zarith
         | _ => rewrite Z.max_l by auto with zarith
         | _ => etransitivity; [ apply Z.le_log2_log2_up | omega ]
         | _ => progress Z.replace_all_neg_with_pos
         | [ H : 0 <= ?x |- _ ]
           => assert (x = 0 \/ x = 1 \/ 1 < x) by omega; clear H; destruct_head' or; subst
         | _ => omega
         | _ => simpl; omega
         | _ => rewrite Z.log2_up_eqn by assumption
         | _ => progress change (Z.log2_up 1) with 0
         end.
Qed.

Lemma land_stabilizes (a b la lb:Z) (Ha:stabilizes_after a la) (Hb:stabilizes_after b lb) : stabilizes_after (Z.land a b) (Z.max la lb).
Proof.
  destruct Ha as [ba Hba]. destruct Hb as [bb Hbb].
  exists (andb ba bb); intros n Hn.
  rewrite Z.land_spec, Hba, Hbb; trivial; lia.
Qed.

Lemma lor_stabilizes (a b la lb:Z) (Ha:stabilizes_after a la) (Hb:stabilizes_after b lb) : stabilizes_after (Z.lor a b) (Z.max la lb).
Proof.
  destruct Ha as [ba Hba]. destruct Hb as [bb Hbb].
  exists (orb ba bb); intros n Hn.
  rewrite Z.lor_spec, Hba, Hbb; trivial; lia.
Qed.

Local Arguments Z.pow !_ !_.
Local Arguments Z.log2_up !_.
Local Arguments Z.add !_ !_.
Lemma testbit_nonneg_iff x
  : (exists l, 0 <= l /\ forall n : Z, l < n -> Z.testbit x n = false) <-> 0 <= x.
Proof.
  split; intro H.
  { destruct H as [l [Hl H]].
    edestruct Z_lt_le_dec; [ | eassumption ].
    pose proof (fun pf n => Z.bits_above_log2_neg x n pf) as H'.
    specialize_by (omega || assumption).
    specialize (H (1 + Z.max l (Z.log2 (Z.pred (- x))))).
    specialize (H' (1 + Z.max l (Z.log2 (Z.pred (- x))))).
    specialize_by (apply Z.max_case_strong; omega).
    congruence. }
  { pose proof (fun n => Z.bits_above_log2 x n H) as Hf.
    eexists; split; [ | eapply Hf ]; auto with zarith. }
Qed.

Lemma stabilizes_bounded_pos (x l:Z) (H:stabilizes_after x l) (Hl : 0 <= l) (Hx : 0 < x)
  : x <= 2^(l + 1) - 1.
Proof.
  assert (Hlt : forall l n, l < n <-> l + 1 <= n) by (intros; omega).
  destruct H as [b H].
  destruct (proj2 (testbit_nonneg_iff x)) as [l' [H0' H1']]; [ omega | ].
  pose proof (Z.testbit_false_bound x (l' + 1)) as Hf.
  pose proof (Z.testbit_false_bound x (l + 1)) as Hf'.
  pose proof (fun pf n => Z.bits_above_log2 x n pf) as Hf''.
  pose proof (fun pf n => Z.log2_lt_pow2 x n pf) as Hlg.
  specialize_by omega.
  setoid_rewrite <- Z.le_ngt in Hf.
  setoid_rewrite <- Z.le_ngt in Hf'.
  setoid_rewrite <- Hlt in Hf; setoid_rewrite <- Hlt in Hf'; clear Hlt.
  setoid_rewrite <- Hlg in Hf''; clear Hlg.
  destruct b; specialize_by (omega || assumption); [ | omega ].
  specialize (H (1 + Z.max l l')).
  specialize (H1' (1 + Z.max l l')).
  specialize_by (apply Z.max_case_strong; omega).
  congruence.
Qed.

Lemma stabilizes_bounded (x l:Z) (H:stabilizes_after x l) (Hl : 0 <= l) : Z.abs x <= 2^(1 + l).
Proof.
  assert (Hlt : forall l n, l < n <-> l + 1 <= n) by (intros; omega).
  rewrite Z.add_comm.
  destruct (Z_zerop x); subst; simpl.
  { cut (0 < 2^(l + 1)); auto with zarith. }
  apply Zabs_ind; intro.
  { etransitivity; [ apply stabilizes_bounded_pos; eauto | ]; omega. }
  { Z.replace_all_neg_with_pos.
    destruct (Z.eq_dec x 1); subst.
    { assert (1 < 2^(l+1)) by auto with zarith.
      omega. }
    { assert (H' : stabilizes_after (Z.pred x) l).
      { destruct H as [b H]; exists (negb b).
        do 2 let x := fresh in intro x; specialize (H x).
        rewrite Z.bits_opp in H by omega.
        destruct b; rewrite ?Bool.negb_true_iff, ?Bool.negb_false_iff in H; assumption. }
      clear H.
      apply stabilizes_bounded_pos in H'; auto; omega. } }
Qed.


Require Import Coq.ZArith.ZArith.
Require Import coqutil.Z.Lia.
Require Import coqutil.Z.BitOps.
Require Import coqutil.Z.bitblast.

Local Open Scope Z_scope.
Local Open Scope bool_scope.

Lemma mod0_divisible_modulo: forall a m n,
    0 < n ->
    0 < m ->
    Z.divide n m ->
    a mod m = 0 ->
    a mod n = 0.
Proof.
  intros.
  unfold Z.divide in H1. destruct H1 as [z H1].
  assert (z < 0 \/ z = 0 \/ 0 < z) as C by blia. destruct C as [C | [ C | C] ].
  - exfalso. Lia.nia.
  - exfalso. Lia.nia.
  - rewrite Z.mul_comm in H1. subst m.
    rewrite Z.rem_mul_r in H2 by blia.
    assert (a mod n < 0 \/ a mod n = 0 \/ 0 < a mod n) as D by blia. destruct D as [D | [D | D ] ].
    + exfalso. pose proof (Z.mod_pos_bound a n H). blia.
    + assumption.
    + pose proof (Z.mod_pos_bound (a / n) z C). exfalso. Lia.nia.
Qed.

Lemma mod_mod_remove_outer: forall a m n,
    0 < m < n ->
    n mod m = 0 ->
    (a mod m) mod n = a mod m.
Proof.
  intros *. intros [A B] C. apply Z.mod_small.
  pose proof (Z.mod_pos_bound a m A). blia.
Qed.

Lemma mod_mod_remove_inner: forall a m n,
    0 < n < m ->
    m mod n = 0 ->
    (a mod m) mod n = a mod n.
Proof.
  intros. rewrite <- Znumtheory.Zmod_div_mod; try blia.
  unfold Z.divide.
  apply Zmod_divides in H0; [|blia].
  destruct H0. subst m.
  exists x. blia.
Qed.

Lemma div_mul_same: forall a b,
    b <> 0 ->
    a / b * b = a - a mod b.
Proof.
  intros.
  pose proof (Zmod_eq_full a b H).
  blia.
Qed.

Lemma sub_mod_exists_q: forall v m,
    0 < m ->
    exists q, v - v mod m = m * q.
Proof.
  intros.
  apply (Zmod_divides (v - v mod m) m); [blia|].
  rewrite <- Zminus_mod_idemp_l.
  rewrite Z.sub_diag.
  rewrite Z.mod_0_l; blia.
Qed.

Lemma shiftr_spec'': forall a n m : Z,
    Z.testbit (Z.shiftr a n) m = (0 <=? m) &&  Z.testbit a (m + n).
Proof.
  intros.
  destruct (Z.leb_spec 0 m).
  - apply Z.shiftr_spec. assumption.
  - rewrite Z.testbit_neg_r; trivial.
Qed.

Lemma shiftr_spec': forall a n m : Z,
    Z.testbit (Z.shiftr a n) m = negb (m <? 0) &&  Z.testbit a (m + n).
Proof.
  intros.
  destruct (Z.ltb_spec m 0).
  - rewrite Z.testbit_neg_r; trivial.
  - apply Z.shiftr_spec. assumption.
Qed.

Definition mask(x start eend: Z): Z :=
  (x - x mod 2 ^ start) mod 2 ^ eend.

Lemma mask_app_plus: forall v i j k,
    0 <= i ->
    i <= j ->
    j <= k ->
    mask v i j + mask v j k = mask v i k.
Proof.
  intros. unfold mask.
  do 2 rewrite <- div_mul_same by (apply Z.pow_nonzero; blia).
  rewrite <-! Z.land_ones by blia.
  rewrite <-! Z.shiftl_mul_pow2 by blia.
  rewrite <- or_to_plus; Z.bitblast.
Qed.

Ltac simpl_pow2_products :=
  repeat match goal with
         | |- context [ 2 ^ ?a * 2 ^ ?b ] =>
           match isZcst a with true => idtac end;
           match isZcst b with true => idtac end;
           let c := eval cbv in (a + b) in change (2 ^ a * 2 ^ b) with (2 ^ c)
         end.

Ltac simpl_Zcsts :=
  repeat match goal with
         | |- context [?op ?a ?b] =>
           match isZcst a with true => idtac end;
           match isZcst b with true => idtac end;
           match op with
           | Z.add => idtac
           | Z.sub => idtac
           | Z.mul => idtac
           end;
           let r := eval cbv in (op a b) in change (op a b) with r
         end.


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (lf2 : natural) (lf1 : natural) (x : natural) (y : natural)
  : natural := mult x (plus y Zero).


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (lf2 : natural) (lf1 : natural) (z : natural) (x : natural)
  : natural := plus lf2 (plus z Zero).


(** Generated by coq-of-ocaml *)
Require Import OCaml.OCaml.

Local Set Primitive Projections.
Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Open Scope type_scope.
Import ListNotations.

Unset Positivity Checking.
Unset Guard Checking.

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

Inductive natural : Set :=
| Zero : natural
| Succ : natural -> natural.

Fixpoint plus (plus_arg0 : natural) (plus_arg1 : natural) {struct plus_arg0}
  : natural :=
  match plus_arg0 with
  | Zero => plus_arg1
  | Succ n => Succ (plus n plus_arg1)
  end.

Fixpoint mult (mult_arg0 : natural) (mult_arg1 : natural) {struct mult_arg0}
  : natural :=
  match mult_arg0 with
  | Zero => Zero
  | Succ n => plus (mult n mult_arg1) mult_arg1
  end.

Definition synth (z : natural) (y : natural) (lf1 : natural) (lf2 : natural)
  : natural := plus z (plus lf2 Zero).