Require Import Essentials.Notations.
Require Import Essentials.Types.
Require Import Essentials.Facts_Tactics.
Require Import Category.Main.
Require Import Functor.Main.

Local Open Scope morphism_scope.

Section Algebras.
  Context {C : Category} (T : (C –≻ C)%functor).

  (** A T-Algebra in category C for an endo-functor T : C → C is a pair (U, h) where
U is an object of C and h : T _o U → U is an arrow in C. *)
  Record Algebra : Type :=
    {
      Alg_Carrier : C;
      Constructors : (T _o Alg_Carrier)%object –≻ Alg_Carrier
    }.

  (** A T-Algebra homomorphism from (U, h) to (U', h') is an arrow g : U → U'
such that the following diagram commutes:

#
<pre>

              T _a g
   T _o U ——————————————> T _o U'
     |                      |
     |                      |
     |                      |
   h |                      | h'
     |                      |
     |                      |
     ↓                      ↓
     U ————–——————————————> U
                g
</pre>
#
 *)
  Record Algebra_Hom (alg alg' : Algebra) : Type :=
    {
      Alg_map : (Alg_Carrier alg) –≻ (Alg_Carrier alg');

      Alg_map_com : ((Constructors alg') ∘ (T _a Alg_map) = Alg_map ∘ (Constructors alg))%morphism
    }.

  Arguments Alg_map {_ _} _.
  Arguments Alg_map_com {_ _} _.

  (** Composition of algebra homomorphisms. The algebra maps are simply composed. *)
  Program Definition Algebra_Hom_compose
          {alg alg' alg'' : Algebra}
          (h : Algebra_Hom alg alg')
          (h' : Algebra_Hom alg' alg'')
    : Algebra_Hom alg alg''
    :=
      {|
        Alg_map := ((Alg_map h') ∘ (Alg_map h))%morphism
      |}.

  Next Obligation.
  Proof.
    destruct h as [alm almcm]; destruct h' as [alm' almcm']; cbn.
    rewrite F_compose.
    rewrite assoc_sym.
    rewrite almcm'.
    rewrite assoc.
    rewrite almcm.
    auto.
  Qed.

  (** Two algebra maps are equal if their underlying maps are. The commutative diagrams
are equated with proof irrelevance. *)
  Lemma Algebra_Hom_eq_simplify (alg alg' : Algebra)
        (ah ah' : Algebra_Hom alg alg')
    : (Alg_map ah) = (Alg_map ah') -> ah = ah'.
  Proof.
    intros; destruct ah; destruct ah'; cbn in *.
    ElimEq.
    PIR.
    trivial.
  Qed.

  (** Composition of algebra homomorphisms is associative. *)
  Theorem Algebra_Hom_compose_assoc
          {alg alg' alg'' alg''' : Algebra}
          (f : Algebra_Hom alg alg')
          (g : Algebra_Hom alg' alg'')
          (h : Algebra_Hom alg'' alg''') :
    (Algebra_Hom_compose f (Algebra_Hom_compose g h))
    = (Algebra_Hom_compose (Algebra_Hom_compose f g) h).
  Proof.
    apply Algebra_Hom_eq_simplify; cbn; auto.
  Qed.

  (** The identity algebra homomorphism. *)
  Program Definition Algebra_Hom_id (alg : Algebra) : Algebra_Hom alg alg :=
    {|
      Alg_map := id
    |}.

  (** Identity algebra homomorphism is the left unit of compositon. *)
  Theorem Algebra_Hom_id_unit_left
          {alg alg' : Algebra}
          (f : Algebra_Hom alg alg') :
    (Algebra_Hom_compose f (Algebra_Hom_id alg')) = f.
  Proof.
    apply Algebra_Hom_eq_simplify; cbn; auto.
  Qed.

  (** Identity algebra homomorphism is the right unit of compositon. *)
  Theorem Algebra_Hom_id_unit_right
          {alg alg' : Algebra}
          (f : Algebra_Hom alg alg') :
    (Algebra_Hom_compose (Algebra_Hom_id alg) f) = f.
  Proof.
    apply Algebra_Hom_eq_simplify; cbn; auto.
  Qed.

  (** Algebras of an endo-functor form a category. *)
  Definition Algebra_Cat : Category :=
    {|
      Obj := Algebra;
      Hom := Algebra_Hom;
      compose := @Algebra_Hom_compose;
      assoc := @Algebra_Hom_compose_assoc;
      assoc_sym := fun _ _ _ _ _ _ _ => eq_sym (@Algebra_Hom_compose_assoc _ _ _ _ _ _ _);
      id := Algebra_Hom_id;
      id_unit_left := @Algebra_Hom_id_unit_left;
      id_unit_right := @Algebra_Hom_id_unit_right
    |}.

End Algebras.

Arguments Alg_Carrier {_ _} _.
Arguments Constructors {_ _} _.
Arguments Algebra_Hom {_ _} _ _.
Arguments Alg_map {_ _ _ _} _.
Arguments Alg_map_com {_ _ _ _} _.
Arguments Algebra_Hom_id {_ _} _.

(** Coalgebras are algebras in the dual category. *)
Section CoAlgebras.
  Context {C : Category}.

  Definition CoAlgebra (T : (C –≻ C)%functor) :=
    @Algebra (C^op) (T^op).

  Definition CoAlgebra_Hom {T : (C –≻ C)%functor} :=
      @Algebra_Hom (C^op) (T^op).

  Definition CoAlgebra_Hom_id {T : (C –≻ C)%functor} :=
    @Algebra_Hom_id  (C^op) (T^op).

  Definition CoAlgebra_Cat (T : (C –≻ C)%functor) :=
    @Algebra_Cat (C^op) (T^op).

End CoAlgebras.


Require Crypto.Algebra.Field.

Module W.
  Section WeierstrassCurves.
    (* Short Weierstrass curves with addition laws. References:
     * <https://hyperelliptic.org/EFD/g1p/auto-shortw.html>
     * <https://cr.yp.to/talks/2007.06.07/slides.pdf>
     * See also:
     * <http://cs.ucsb.edu/~koc/ccs130h/2013/EllipticHyperelliptic-CohenFrey.pdf> (page 79)
     *)

    Context {F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {field:@Algebra.Hierarchy.field F Feq Fzero Fone Fopp Fadd Fsub Fmul Finv Fdiv} {Feq_dec:Decidable.DecidableRel Feq} {char_ge_3:@Ring.char_ge F Feq Fzero Fone Fopp Fadd Fsub Fmul (BinNat.N.succ_pos (BinNat.N.two))}.
    Local Infix "=" := Feq : type_scope. Local Notation "a <> b" := (not (a = b)) : type_scope.
    Local Notation "x =? y" := (Decidable.dec (Feq x y)) (at level 70, no associativity) : type_scope.
    Local Notation "x =? y" := (Sumbool.bool_of_sumbool (Decidable.dec (Feq x y))) : bool_scope.
    Local Infix "+" := Fadd. Local Infix "*" := Fmul.
    Local Infix "-" := Fsub. Local Infix "/" := Fdiv.
    Local Notation "- x" := (Fopp x).
    Local Notation "x ^ 2" := (x*x) (at level 30). Local Notation "x ^ 3" := (x*x^2) (at level 30).
    Local Notation "'∞'" := unit : type_scope.
    Local Notation "'∞'" := (inr tt) : core_scope.

    Local Notation "( x , y )" := (inl (pair x y)).
    Local Open Scope core_scope.

    Context {a b: F}.

    Definition point := { P | match P with
                              | (x, y) => y^2 = x^3 + a*x + b
                              | ∞ => True
                              end }.
    Definition coordinates (P:point) : F*F + ∞ := let (xyi,_) := P in xyi.

    Definition eq (P1 P2:point) :=
      match coordinates P1, coordinates P2 with
      | (x1, y1), (x2, y2) => x1 = x2 /\ y1 = y2
      | ∞, ∞ => True
      | _, _ => False
      end.

    Program Definition zero : point := ∞.

    Local Notation "0" := Fzero.  Local Notation "1" := Fone.
    Local Notation "2" := (1+1). Local Notation "3" := (1+2).

    Program Definition add (P1 P2:point) : point :=
      match coordinates P1, coordinates P2 return F*F+∞ with
      | (x1, y1), (x2, y2) =>
        if x1 =? x2
        then
          if y2 =? -y1
          then ∞
          else let k := (3*x1^2+a)/(2*y1) in
               let x3 := k^2-x1-x2 in
               let y3 := k*(x1-x3)-y1 in
               (x3, y3)
        else let k := (y2-y1)/(x2-x1) in
             let x3 := k^2-x1-x2 in
             let y3 := k*(x1-x3)-y1 in
             (x3, y3)
      | ∞, ∞ => ∞
      | ∞, _ => coordinates P2
      | _, ∞ => coordinates P1
      end.
    Next Obligation.
      cbv [coordinates]; BreakMatch.break_match; trivial; Field.fsatz.
    Qed.

    Fixpoint mul (n:nat) (P : point) : point :=
      match n with
      | O => zero
      | S n' => add P (mul n' P)
      end.
  End WeierstrassCurves.
End W.

Declare Scope W_scope.
Delimit Scope W_scope with W.
Infix "+" := W.add : W_scope.
Infix "*" := W.mul : W_scope.


Require Export SystemFR.Judgments.

Lemma subtype_refl:
  forall Θ Γ T,
    [[ Θ; Γ ⊨ T <: T ]].
Proof.
  unfold open_subtype; steps.
Qed.

Lemma subtype_trans:
  forall Θ Γ T1 T2 T3,
    [[ Θ; Γ ⊨ T1 <: T2 ]] ->
    [[ Θ; Γ ⊨ T2 <: T3 ]] ->
    [[ Θ; Γ ⊨ T1 <: T3 ]].
Proof.
  unfold open_subtype; steps.
Qed.


Require Import ChargeCore.SepAlg.UUSepAlg.
Require Import ChargeCore.SepAlg.SepAlg.

Require Import Relation_Definitions CRelationClasses Morphisms.

Set Implicit Arguments.
Unset Strict Implicit.
Set Maximal Implicit Insertion.

Section RelProducts.
  Context {A B : Type} {relA : relation A} {relB : relation B}.
  Context {HA: Equivalence relA}.
  Context {HB: Equivalence relB}.

  Definition rel_prod : relation (A * B) :=
    fun p1 p2 => (relA (fst p1) (fst p2) /\ relB (snd p1) (snd p2)).

  Global Instance prod_proper : Proper (relA ==> relB ==> rel_prod) (@pair A B).
  Proof.
    intros a a' Ha b b' Hb; split; assumption.
  Qed.

  Global Instance equiv_prod : Equivalence rel_prod.
  Proof.
    split.
      intros [a b]; split; reflexivity.
      intros [a1 b1] [a2 b2] [Ha Hb]; split; symmetry; assumption.
    intros [a1 b1] [a2 b2] [a3 b3] [Ha12 Hb12] [Ha23 Hb23];
      split; etransitivity; eassumption.
  Qed.

End RelProducts.

Section SAProd.
  Context A B `{HA: SepAlg A} `{HB: SepAlg B}.

  Instance SepAlgOps_prod: SepAlgOps (A * B) :=
  { sa_unit ab := sa_unit (fst ab) /\ sa_unit (snd ab)
  ; sa_mul a b c :=
      sa_mul (fst a) (fst b) (fst c) /\
      sa_mul (snd a) (snd b) (snd c)
  }.

  Definition SepAlg_prod: SepAlg (rel := rel_prod (relA := rel) (relB := rel0)) (A * B).
  Proof.
    esplit.
    - eapply equiv_prod.
    - intros * [Hab Hab']. split; apply sa_mulC; assumption.
    - intros * [Habc Habc'] [Hbc Hbc'].
      destruct (sa_mulA Habc Hbc) as [exA []].
      destruct (sa_mulA Habc' Hbc') as [exB []].
      exists (exA, exB). split; split; assumption.
    - intros [a b].
      destruct (sa_unit_ex a) as [ea [Hea Hmulea]].
      destruct (sa_unit_ex b) as [eb [Heb Hmuleb]].
      exists (ea,eb). split; split; assumption.
    - intros * [Hunita Hunitb] [Hmula Hmulb].
      split; eapply sa_unit_eq; eassumption.
    - intros ab ab' [Hab Hab']. simpl. rewrite Hab, Hab'. reflexivity.
    - intros [a1 a2] [b1 b2] [c1 c2] [d1 d2] Heq [H1 H2].
      unfold Equivalence.equiv in Heq; destruct Heq; simpl in *.
      rewrite <- H, <- H0; intuition.
  Qed.

  Lemma subheap_prod (a a' : A) (b b' : B)
  : subheap (a, b) (a', b') <-> subheap a a' /\ subheap b b'.
  Proof.
    split; [intros [c [H1 H2]]| intros [[c H1] [d H2]]]; simpl in *.
    + destruct c as [c d]; simpl in *; split.
      * exists c. apply H1.
      * exists d. apply H2.
    + exists (c, d); simpl; split.
      * apply H1.
      * apply H2.
  Qed.

  Lemma sa_mul_split (a b c : A) (a' b' c' : B)
  : sa_mul (a, a') (b, b') (c, c') <-> sa_mul a b c /\ sa_mul a' b' c'.
  Proof.
    split; intros; simpl in *; auto.
  Qed.

End SAProd.

Section UUSAProd.
  Context A B `{HA : UUSepAlg A} `{HB: UUSepAlg B}.

  Local Existing Instance SepAlgOps_prod.
  Local Existing Instance SepAlg_prod.

  Instance UUSepAlg_prod : UUSepAlg (rel := rel_prod (relA := rel) (relB := rel0)) (A * B).
  Proof.
    split.
    + apply _.
    + intros. destruct H as [H1 H2]. destruct u; simpl in *.
      split; apply uusa_unit; assumption.
  Qed.

End UUSAProd.

Section SASum.
  Context A B `{HA: SepAlg A} `{HB: SepAlg B}.

  Global Instance SepAlgOps_sum: SepAlgOps (A + B) := {|
    sa_unit ab :=
      match ab with
      | inl a => sa_unit a
      | inr b => sa_unit b
      end;
    sa_mul a b c :=
      match a , b , c with
      | inl a , inl b , inl c => sa_mul a b c
      | inr a , inr b , inr c => sa_mul a b c
      | _ , _ , _ => False
      end
   |}.

  Variant sum_eq : A + B -> A + B -> Prop :=
  | sum_eq_L {a a'} (_ : rel a a')
    : sum_eq (inl a) (inl a')
  | sum_eq_R {b b'} (_ : rel0 b b')
    : sum_eq (inr b) (inr b').

  Global Instance SepAlg_sum: @SepAlg _ sum_eq _.
  Proof.
    econstructor.
    { constructor.
      { compute. destruct x; constructor; reflexivity. }
      { compute. inversion 1; constructor; subst; symmetry; eauto. }
      { compute. inversion 1; subst; inversion 1; subst; constructor; subst; etransitivity; eauto. } }
    { destruct a; simpl; try destruct b; try destruct c; simpl; eauto.
      eapply sa_mulC.
      destruct b0; auto.
      eapply sa_mulC. }
    { intros [] [] [] [] [];  simpl;
          try solve [ eauto | intros ; contradiction ].
      { intros H H'. destruct (@sa_mulA _ _ _ _ _ _ _ _ _ H H').
        exists (inl x); eauto. }
      { intros H H'. destruct (@sa_mulA _ _ _ _ _ _ _ _ _ H H').
        exists (inr x); eauto. } }
    { intros [].
      { destruct (sa_unit_ex a).
        exists (inl x). auto. }
      { destruct (sa_unit_ex b).
        exists (inr x). auto. } }
    { intros [] [] []; simpl; intros; try contradiction; constructor.
      eapply sa_unit_eq; eauto.
      eapply sa_unit_eq; eauto. }
    { constructor.
      { inversion H; subst; simpl; eauto using sa_unit_proper.
        eapply sa_unit_proper; symmetry; eauto.
        eapply sa_unit_proper; symmetry; eauto. }
      { inversion H; subst; simpl; eauto using sa_unit_proper.
        eapply sa_unit_proper; eauto.
        eapply sa_unit_proper; eauto. } }
    { inversion 1; subst; simpl; eauto.
      { destruct c; destruct d; eauto.
        eapply sa_mul_mon; eauto. }
      { destruct c; destruct d; eauto.
        eapply sa_mul_mon; eauto. } }
  Qed.
End SASum.


Require Import Coq.Lists.List. Import ListNotations.
Require Import Coq.Logic.Classical.

Definition funname := nat.
Definition varname := nat.

Inductive term: Type :=
| Var: varname -> term
| Fun: funname -> list term -> term.

(* clauses consist of positive or negated literals *)
Inductive literal: Type :=
| Pos: term -> literal
| Neg: term -> literal.

Definition atm_of(l: literal): term := match l with Pos t | Neg t => t end.

(* clauses are disjunctions of literals *)
Definition clause := list literal.

(* a goal is a list of clauses implying False *)
Definition goal := list clause.

Definition set(T: Type) := T -> Prop.

(* A Herbrand interpretation ("model") is a set of ground terms considered true *)
Definition model := set term.

Definition satisfies_literal(m: model)(l: literal): Prop :=
  match l with
  | Pos t => m t
  | Neg t => ~ m t
  end.

Definition satisfies_clause(m: model)(c: clause): Prop :=
  fold_right (fun l acc => satisfies_literal m l \/ acc) False c.

Definition satisfies_clauses_listbased(m: model)(cs: list clause): Prop :=
  fold_right (fun c acc => satisfies_clause m c /\ acc) True cs.

Definition satisfiable_listbased(cs: list clause): Prop :=
  exists (m: model), satisfies_clauses_listbased m cs.

Definition satisfies_clauses(m: model)(cs: set clause): Prop :=
  forall c, cs c -> satisfies_clause m c.

Definition satisfiable(cs: set clause): Prop :=
  exists (m: model), satisfies_clauses m cs.

Definition substitution := varname -> option term.

Definition apply_subst_in_term(s: substitution): term -> term :=
  fix rec t :=
    match t with
    | Var x =>
      match s x with
      | Some u => u
      | None => Var x
      end
    | Fun name args => Fun name (map rec args)
    end.

Definition apply_subst_in_literal(s: substitution)(l: literal): literal :=
  match l with
  | Pos t => Pos (apply_subst_in_term s t)
  | Neg t => Neg (apply_subst_in_term s t)
  end.

Definition apply_subst_in_clause(s: substitution)(cl: clause): clause :=
  map (apply_subst_in_literal s) cl.

Definition is_ground_term(t: term): Prop := forall s, apply_subst_in_term s t = t.

Definition is_ground_literal(l: literal): Prop := is_ground_term (atm_of l).

Definition is_ground_clause(c: clause): Prop := Forall is_ground_literal c.

Definition grounding_of_clause(c: clause): set clause :=
  fun c' => is_ground_clause c' /\ exists s, c' = apply_subst_in_clause s c.

(* closer to IsaFOL:
Definition is_ground_subst(s: substitution): Prop :=
  forall (t: term), is_ground_term (apply_subst_in_term s t).

Definition grounding_of_clause(c: clause): set clause :=
  fun c' => exists s, is_ground_subst s /\ c' = apply_subst_in_clause s c.
*)

Definition union{T: Type}(A B: set T): set T :=
  fun x => A x \/ B x.

Definition empty{T: Type}: set T := fun x => False.

Definition grounding_of_clauses(cs: list clause): set clause :=
  fold_right (fun c acc => union (grounding_of_clause c) acc) empty cs.

Definition goal_unsatisfiable(g: goal): Prop := ~ satisfiable (grounding_of_clauses g).

Definition fun_ctx := funname -> forall (T: Type), T -> Prop.
Definition var_ctx := varname -> forall (T: Type), T -> Prop.

Inductive interp_term: fun_ctx -> var_ctx -> term -> forall {T: Type}, T -> Prop :=
| interp_var: forall (Gf: fun_ctx) (Gv: var_ctx) x T v,
    Gv x T v ->
    interp_term Gf Gv (Var x) v
| interp_fun_nil: forall (Gf: fun_ctx) (Gv: var_ctx) name F f,
    Gf name F f ->
    interp_term Gf Gv (Fun name nil) f
| interp_fun_cons: forall Gf Gv name arg args A R (t1: A -> R) (t2: A),
    interp_term Gf Gv (Fun name args) t1 ->
    interp_term Gf Gv arg t2 ->
    interp_term Gf Gv (Fun name (arg :: args)) (t1 t2). (* argument order reads the wrong way *)

Inductive interp_lit: fun_ctx -> var_ctx -> literal -> Prop -> Prop :=
| interp_Pos: forall Gf Gv t P,
    interp_term Gf Gv t P ->
    interp_lit Gf Gv (Pos t) P
| interp_Neg: forall Gf Gv t P,
    interp_term Gf Gv t P ->
    interp_lit Gf Gv (Neg t) (~ P).

Inductive interp_clause'': fun_ctx -> var_ctx -> clause -> Prop -> Prop :=
| interp_False: forall Gf Gv,
    interp_clause'' Gf Gv nil False
| interp_or: forall Gf Gv c cs P Ps,
    interp_lit Gf Gv c P ->
    interp_clause'' Gf Gv cs Ps ->
    interp_clause'' Gf Gv (c :: cs) (P \/ Ps).

Inductive Eq: forall (T: Type) (x: T) (T': Type) (x': T'), Prop :=
| Refl: forall (T: Type) (x: T), Eq T x T x.
(*
Inductive Wrap: Prop :=
| wrap(T: Type)(x: T): Wrap.
*)

Definition empty_ctx: nat -> forall (T: Type), T -> Prop :=
  fun n T v => False.

Definition cons_ctx(ctx: nat -> forall (T: Type), T -> Prop)
   (newName: nat)(newT: Type)(newV: newT): nat -> forall (T: Type), T -> Prop :=
  fun n => if PeanoNat.Nat.eq_dec n newName then Eq newT newV else ctx n.

Definition singleton_ctx(n: nat)(T: Type)(v: T) := cons_ctx empty_ctx n T v.

Inductive interp_clause': fun_ctx -> var_ctx -> clause -> Prop -> Prop :=
| interp_done: forall Gf Gv c P,
    interp_clause'' Gf Gv c P ->
    interp_clause' Gf Gv c P
| interp_forall: forall Gf Gv c U (P: U -> Prop) fresh,
    (forall T v, ~ Gv fresh T v) ->
    (forall (u: U), interp_clause' Gf (cons_ctx Gv fresh U u) c (P u)) ->
    interp_clause' Gf Gv c (forall (u: U), P u).

Definition interp_clause(Gf: fun_ctx): clause -> Prop -> Prop :=
  interp_clause' Gf empty_ctx.

Inductive interp_goal'': fun_ctx -> list clause -> Prop -> Prop :=
| interp_goal_nil: forall Gf,
    interp_goal'' Gf nil False
| interp_goal_cons: forall Gf c cs P Ps,
    interp_clause Gf c P ->
    interp_goal'' Gf cs Ps ->
    interp_goal'' Gf (c :: cs) (P -> Ps).

Inductive interp_goal': fun_ctx -> list clause -> Prop -> Prop :=
| interp_goal_done: forall Gf c P,
    interp_goal'' Gf c P ->
    interp_goal' Gf c P
| interp_forall_fun: forall Gf c (A B: Type) (P: (A -> B) -> Prop) fresh,
    (forall T v, ~ Gf fresh T v) ->
    (forall (f: A -> B), interp_goal' (cons_ctx Gf fresh (A -> B) f) c (P f)) ->
    interp_goal' Gf c (forall (f: A -> B), P f).

Definition interp_goal: list clause -> Prop -> Prop := interp_goal' empty_ctx.

(* Example: The clause (P \/ ~ P) holds in all models *)
Lemma exmiddle_in_model: forall m, satisfies_clause m [Pos (Fun 0 []); Neg (Fun 0 [])].
Proof.
  intros. simpl.
  destruct (classic (m (Fun 0 []))); auto.
Qed.

(* how can we conclude from this that this clause also is derivable in Coq's logic?
   -> looks like the completeness theorem
 *)

(* could also call it completeness in the sense that Coq's logic is complete for
   satisfies_clause *)
Lemma interp_clause''_sound: forall Gf Gv c P,
    interp_clause'' Gf Gv c P ->
    (forall m, satisfies_clause m c) ->
    P.
Proof.
  induction 1; intros; simpl in *.
  - apply H. intro. apply True.
  - destruct (classic (forall m : model, satisfies_clause m cs)) as [C | C].
    + auto.
    + (* ? *)
Abort.

(*
Lemma interp_literal_sound: forall Gf Gv l P,
    interp_lit Gf Gv l P ->
    (forall m, satisfies_literal m l) ->
    P.
Proof.
  intros. destruct H.
  - simpl in *.

Lemma interp_clause_grounding: forall Gf Gv c P,
    interp_clause'' Gf Gv c P ->
    forall gc, grounding_of_clause c gc
*)

Lemma interp_goal_herbrand_sound: forall g P,
    interp_goal g P ->
    goal_unsatisfiable g ->
    P.
Admitted.

(* tells if goal is satisfiable *)
Definition prover(g: goal): bool. Admitted.

Theorem prover_sound: forall g, prover g = false -> goal_unsatisfiable g.
Admitted.

(* this goal does not hold, but that's how we'd prove goals *)
Lemma test2: forall (P: nat -> nat -> Prop),
    (forall a b c, ~ P a b \/ ~ P b c \/ P a c \/ False) ->
    False.
Proof.
  eapply interp_goal_herbrand_sound.

  (* Reification: TODO automate *)
  { eapply interp_forall_fun with (fresh := 0). { cbv. auto. }
    intros.
    eapply interp_goal_done.
    eapply interp_goal_cons; [|eapply interp_goal_nil].
  eapply interp_forall with (fresh := 0). { cbv. auto. }
  intros.
  eapply interp_forall with (fresh := 1). { cbv. auto. }
  intros.
  eapply interp_forall with (fresh := 2). { cbv. auto. }
  intros.
  eapply interp_done.
  repeat eapply interp_or.
  { eapply interp_Neg.
    eapply interp_fun_cons with (name := 0).
    - eapply interp_fun_cons.
      + eapply interp_fun_nil. cbv. apply Refl.
      + eapply interp_var with (x := 0). cbv. apply Refl.
    - eapply interp_var with (x := 1). cbv. apply Refl.
  }
  { eapply interp_Neg.
    eapply interp_fun_cons with (name := 0).
    - eapply interp_fun_cons.
      + eapply interp_fun_nil. cbv. apply Refl.
      + eapply interp_var with (x := 1). cbv. apply Refl.
    - eapply interp_var with (x := 2). cbv. apply Refl.
  }
  { eapply interp_Pos.
    eapply interp_fun_cons with (name := 0).
    - eapply interp_fun_cons.
      + eapply interp_fun_nil. cbv. apply Refl.
      + eapply interp_var with (x := 0). cbv. apply Refl.
    - eapply interp_var with (x := 2). cbv. apply Refl.
  }
  { eapply interp_False. } }

  apply prover_sound.

  (* now if "prover" was implemented, we could just run "vm_compute", which would
     reduce the goal to "false = false", and then apply "reflexivity" *)

Admitted.


(** 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) : natural := lf1.


Set Implicit Arguments.
Require Import List Morphisms FinFun
        std.tactics std.ars.basic std.ars.confluence.
Import ListNotations.

Section ListRelations.

  Variable (X : Type) (R: X -> X -> Prop).
  Inductive lstep: list X -> list X -> Prop :=
  | stepHead s s' A: R s s' -> lstep (s :: A) (s' :: A)
  | stepTail s A A': lstep A A' -> lstep (s :: A) (s :: A').

  Hint Constructors lstep.

  Lemma lstep_cons_nil S:
    lstep S nil -> False.
  Proof.
    intros. inv H.
  Qed.

  Lemma lsteps_cons_nil s S:
    star lstep (s :: S) nil -> False.
  Proof.
    intros. remember (s :: S) as S'. remember nil as T.  revert S s HeqS' HeqT.
    induction H.
    - intros; subst; discriminate.
    - intros; subst. inv H; eapply IHstar; eauto.
  Qed.

  Lemma lstep_nil_cons S:
    lstep nil S -> False.
  Proof.
    intros H. inv H.
  Qed.

  Lemma lsteps_nil_cons s S:
    star lstep nil (s :: S) -> False.
  Proof.
    intros H. inv H.
    eapply lstep_nil_cons; eauto.
  Qed.

  Lemma lsteps_cons_inv s t S T:
    star lstep (s :: S) (t :: T) -> star R s t /\ star lstep S T.
  Proof.
    intros H. remember (s :: S) as S'. remember (t :: T) as T'.
    revert s t S T HeqS' HeqT'.
    induction H; intros.
    - subst. injection HeqT' as ??; subst. intuition.
    - subst. inv H.
      + destruct (IHstar s' t S T); eauto.
      + destruct (IHstar s t A' T); eauto.
  Qed.

  Global Instance lsteps_cons :
    Proper (star R ++> star lstep ++> star lstep) cons.
  Proof.
    intros ??; induction 1; intros ??; induction 1; eauto.
  Qed.

  Lemma confluence_lstep:
    confluent R -> confluent lstep.
  Proof.
    intros conf ?. induction x; intros.
    - inv H. inv H0. exists nil; eauto. inv H. inv H1.
    - destruct y, z; try solve [exfalso; eapply lsteps_cons_nil; eauto].
      eapply lsteps_cons_inv in H; eapply lsteps_cons_inv in H0.
      intuition; destruct (IHx _ _ H2 H3) as [V].
      destruct (conf _ _ _ H1 H) as [v].
      exists (v :: V).
      now rewrite H5, H0. now rewrite H6, H4.
  Qed.

  Hint Resolve confluence_lstep.

  Lemma normal_lstep_in A:
    Normal lstep A -> forall x, In x A  -> Normal R x.
  Proof.
    induction A; cbn; intuition; subst; eauto.
    intros ? H1. eapply H. constructor. eassumption.
    eapply IHA; eauto. intros ? H2. eapply H.
    econstructor 2; eauto.
  Qed.

  Lemma normal_in_lstep A:
    (forall x, In x A  -> Normal R x) -> Normal lstep A.
  Proof.
    induction A; cbn; intuition.
    - intros ? H1. inv H1.
    - intros ? H1. inv H1.
      eapply H; eauto.
      eapply IHA; eauto.
  Qed.

  Lemma lstep_normal_cons_l a A:
    Normal lstep (a :: A) -> Normal R a.
  Proof. intros ? ? ?. eapply H; econstructor; eauto. Qed.

  Lemma lstep_normal_cons_r a A:
    Normal lstep (a :: A) -> Normal lstep A.
  Proof. intros ? ? ?. eapply H; econstructor 2; eauto. Qed.

  Lemma lstep_normal_cons a A:
    Normal R a -> Normal lstep A -> Normal lstep (a :: A).
  Proof. intros ? ? ? ?. inv H1; firstorder.  Qed.

  Lemma lstep_normal_nil:
    Normal lstep nil.
  Proof. intros ? H; inv H. Qed.

  Hint Resolve
       lstep_normal_nil
       lstep_normal_cons_l
       lstep_normal_cons_r
       lstep_normal_cons.

  Hint Resolve normal_lstep_in normal_in_lstep.

  Lemma equiv_lstep_cons_inv s t S T:
    equiv lstep (s :: S) (t :: T) -> equiv R s t /\ equiv lstep S T.
  Proof.
    intros H. remember (s :: S) as S'. remember (t :: T) as T'.
    revert s t S T HeqS' HeqT'.
    induction H; intros.
    - subst. injection HeqT' as ??; subst; intuition.
    - subst. inv H.
      + destruct x'. eapply lstep_cons_nil in H1 as [].
        edestruct IHstar; eauto. inv H1.
        * intuition.
          transitivity x; eauto.
        * intuition. transitivity x'; eauto.
      + destruct x'. eapply lstep_nil_cons in H1 as [].
        edestruct IHstar; eauto. inv H1; intuition.
        * transitivity x; eauto.
        * transitivity x'; eauto.
  Qed.

  Global Instance equiv_lstep_cons_proper:
    Proper (equiv R ++> equiv lstep ++> equiv lstep) cons.
  Proof.
    intros ??; induction 1; intros ??; induction 1; eauto.
    - rewrite <-IHstar. destruct H.
      eauto. symmetry. eauto.
    - rewrite <-(IHstar x0 x0); try reflexivity.
      destruct H. eauto. symmetry. eauto.
    - rewrite <-IHstar0.
      destruct H1. eauto. symmetry. eauto.
  Qed.

  Lemma not_equiv_lstep_nil_cons a A:
    ~ equiv lstep nil (a :: A).
  Proof.
    intros H; inv H; inv H0; inv H.
  Qed.

  Lemma list_equiv_ind (P: list X -> list X -> Prop):
    P nil nil ->
    (forall s t S T, equiv R s t -> equiv lstep S T -> P S T -> P (s :: S) (t :: T)) ->
    forall S T, equiv lstep S T -> P S T.
  Proof.
    intros B IH S T H; induction S in T, H |-*; destruct T; eauto.
    - exfalso; eapply not_equiv_lstep_nil_cons; eauto.
    - exfalso; eapply not_equiv_lstep_nil_cons; symmetry; eauto.
    - eapply equiv_lstep_cons_inv in H as (? & ?).
      eapply IH; eauto.
  Qed.

End ListRelations.

Hint Constructors lstep.

Hint Resolve
     lstep_normal_nil
     lstep_normal_cons_l
     lstep_normal_cons_r
     lstep_normal_cons.

Hint Resolve confluence_lstep.
Hint Resolve normal_lstep_in normal_in_lstep.


(* Contribution to the Coq Library   V6.3 (July 1999)                    *)

(****************************************************************************)
(*                                                                          *)
(*                           Group Theory in Coq                            *)
(*                                                                          *)
(*                                                                          *)
(*                                Coq V5.10                                 *)
(*									    *)
(*			         Gilles Kahn 				    *)
(*									    *)
(*                                  INRIA                                   *)
(*                             Sophia-Antipolis                             *)
(*									    *)
(*				 January 1996				    *)
(*                                                                          *)
(****************************************************************************)

Require Import Ensembles.
Require Import Laws.
Require Import Group_definitions.
Require Import gr.
Parameter U : Type.
Parameter Gr : Group U.

Definition G : Ensemble U := G_ U Gr.

Definition star : U -> U -> U := star_ U Gr.

Definition inv : U -> U := inv_ U Gr.

Definition e : U := e_ U Gr.

Definition G0' : forall a b : U, In U G a -> In U G b -> In U G (star a b) :=
  G0 U Gr.

Definition G1' : forall a b c : U, star a (star b c) = star (star a b) c :=
  G1 U Gr.

Definition G2a' : In U G e := G2a U Gr.

Definition G2b' : forall a : U, star e a = a := G2b U Gr.

Definition G2c' : forall a : U, star a e = a := G2c U Gr.

Definition G3a' : forall a : U, In U G a -> In U G (inv a) := G3a U Gr.

Definition G3b' : forall a : U, star a (inv a) = e := G3b U Gr.

Definition G3c' : forall a : U, star (inv a) a = e := G3c U Gr.
Hint Resolve G1'.
Hint Resolve G2a' G2b' G2c'.
Hint Resolve G3a' G3b' G3c'.
Hint Resolve G0'.

Definition triv1' : forall a b : U, star (inv a) (star a b) = b := triv1 U Gr.

Definition triv2' : forall a b : U, star (star b a) (inv a) = b := triv2 U Gr.

Definition resolve' : forall a b : U, star b a = e -> b = inv a :=
  resolve U Gr.

Definition self_inv' : e = inv e := self_inv U Gr.

Definition inv_star' :
  forall a b : U, star (inv b) (inv a) = inv (star a b) :=
  inv_star U Gr.

Definition cancellation' : forall a b : U, star a b = a -> b = e :=
  cancellation U Gr.

Definition inv_involution' : forall a : U, a = inv (inv a) :=
  inv_involution U Gr.
Hint Resolve triv1' triv2' inv_star' resolve' inv_involution'.

Section Elements.
Variable H : Group U.
Variable sub : subgroup U H Gr.

Lemma l1 : Included U (G_ U H) G.
Proof.
elim sub; auto with sets.
Qed.
Hint Resolve l1.

Lemma eH_in_G : In U G (e_ U H).
Proof.
elim sub.
elim H; auto with sets.
Qed.
Hint Resolve eH_in_G.

Lemma starH_is_star : star_ U H = star.
Proof.
elim sub; auto with sets.
Qed.
Hint Resolve starH_is_star.

Lemma eh_is_e : e_ U H = e.
Proof.
apply cancellation' with (a := e_ U H).
rewrite <- starH_is_star; auto with sets.
Qed.
Hint Resolve eh_is_e.

Theorem invH_is_inv : forall a : U, In U (G_ U H) a -> inv_ U H a = inv a.
Proof.
intros a H'.
apply resolve'; auto with sets.
rewrite <- starH_is_star.
rewrite <- eh_is_e.
generalize H'; clear H'.
elim H; auto with sets.
Qed.

Theorem Subgroup_inhabited : Inhabited U (G_ U H).
Proof.
apply Inhabited_intro with (x := e_ U H); auto with sets.
Qed.

Theorem star_endo : endo_operation U (G_ U H) star.
Proof.
rewrite <- starH_is_star; auto with sets.
Qed.

Theorem inv_endo : endo_function U (G_ U H) inv.
Proof.
red in |- *; intros a H'; rewrite <- (invH_is_inv a); auto with sets.
Qed.

End Elements.

Section Premier.

Variable H : Ensemble U.
Variable witness : U.
Variable inhabited : In U H witness.
Variable subset : Included U H G.
Variable hstar : endo_operation U H star.
Variable hinv : endo_function U H inv.
Hint Resolve inhabited subset hstar hinv.

Let assoc : associative U star.
Proof.
auto with sets.
Qed.
Hint Resolve assoc.

Let eH : U := star (inv witness) witness.

Let eH_in_H : In U H eH.
Proof.
unfold eH at 1 in |- *; auto with sets.
Qed.

Let eH_left_neutral : left_neutral U star eH.
Proof.
unfold eH, left_neutral in |- *.
rewrite (G3c' witness); auto with sets.
Qed.

Let eH_right_neutral : right_neutral U star eH.
Proof.
unfold eH, left_neutral in |- *.
rewrite (G3c' witness); auto with sets.
Qed.

Let inv_left_inverse : left_inverse U star inv eH.
Proof.
unfold eH, left_inverse in |- *.
intro x.
rewrite (G3c' x); auto with sets.
Qed.

Let inv_right_inverse : right_inverse U star inv eH.
Proof.
unfold eH, right_inverse in |- *.
intro x.
rewrite (G3b' x); auto with sets.
Qed.

Let GrH : Group U :=
  group U H star inv eH hstar assoc eH_in_H eH_left_neutral eH_right_neutral
    hinv inv_right_inverse inv_left_inverse.
Hint Resolve Definition_of_subgroup.

Theorem T_1_6_2 : Setsubgroup U H Gr.
Proof.
unfold Setsubgroup at 1 in |- *; simpl in |- *.
exists GrH.
unfold GrH in |- *; simpl in |- *; auto with sets.
Qed.

End Premier.

Require Import Zbase.
Require Import Z_succ_pred.
Require Import Zadd.

Definition exp : Z -> U -> U.
Proof.
intros n a.
elim n; clear n.
exact e.
intro n; elim n; clear n.
exact a.
intros n valrec.
exact (star a valrec).
intro n; elim n; clear n.
exact (inv a).
intros n valrec.
exact (star (inv a) valrec).
Defined.

Theorem exp_endo : forall (a : U) (n : Z), In U G a -> In U G (exp n a).
Proof.
intros a n; elim n; simpl in |- *; auto with sets.
intro n0; elim n0; simpl in |- *; auto with sets.
intro n0; elim n0; simpl in |- *; auto with sets.
Qed.
Hint Resolve exp_endo.

Lemma exp_unfold_pos :
 forall (a : U) (n : nat),
 In U G a -> exp (pos (S n)) a = star a (exp (pos n) a).
Proof.
auto with sets.
Qed.

Lemma exp_unfold_neg :
 forall (a : U) (n : nat),
 In U G a -> exp (neg (S n)) a = star (inv a) (exp (neg n) a).
Proof.
auto with sets.
Qed.

Lemma exp_l1 :
 forall (a : U) (n : nat),
 In U G a -> star a (exp (neg (S n)) a) = exp (neg n) a.
Proof.
intros a n H'; try assumption.
rewrite (exp_unfold_neg a); trivial with sets.
rewrite (inv_involution' a); trivial with sets.
cut (inv (inv (inv a)) = inv a).
intro H'0; rewrite H'0; apply triv1'; auto with sets.
rewrite <- (inv_involution' a); auto with sets.
Qed.
Hint Resolve exp_l1.

Lemma exp_l2 :
 forall (a : U) (n : Z), In U G a -> star a (exp n a) = exp (succZ n) a.
Proof.
intros a n; elim n; auto with sets.
intro n0; elim n0; auto with sets.
intros n1 H' H'0.
rewrite (exp_l1 a n1); auto with sets.
Qed.

Lemma exp_l2' :
 forall (a : U) (n : Z), In U G a -> star (inv a) (exp n a) = exp (predZ n) a.
Proof.
intros a n; elim n; auto with sets.
intro n0; elim n0; auto with sets.
intros n1 H' H'0.
rewrite (exp_unfold_pos a n1); trivial with sets.
Qed.
Hint Resolve exp_l2 exp_l2' exp_unfold_pos exp_unfold_neg.
Hint Immediate sym_eq.

Theorem add_exponents :
 forall (a : U) (m n : Z),
 In U G a -> star (exp m a) (exp n a) = exp (addZ m n) a.
Proof.
intros a m; elim m; auto with sets.
intro n; elim n; auto with sets.
intros n0 H' n1 H'0.
rewrite (tech_add_pos_succZ n0 n1).
rewrite <- (exp_l2 a (addZ (pos n0) n1)); trivial with sets.
rewrite (exp_unfold_pos a n0); trivial with sets.
rewrite <- (H' n1); trivial with sets.
auto with sets.
intro n; elim n.
simpl in |- *.
intros n0 H'.
apply exp_l2'; auto with sets.
intros n0 H' n1 H'0.
rewrite (tech_add_neg_predZ n0 n1).
rewrite <- (exp_l2' a (addZ (neg n0) n1)); trivial with sets.
rewrite <- (H' n1); trivial with sets.
rewrite (exp_unfold_neg a n0); trivial with sets.
auto with sets.
Qed.

Lemma exp_commut1 :
 forall (a : U) (m : Z), In U G a -> star (exp m a) a = star a (exp m a).
Proof.
intros a m H'.
change (star (exp m a) (exp IZ a) = star (exp IZ a) (exp m a)) in |- *.
rewrite (add_exponents a m IZ); trivial with sets.
rewrite (add_exponents a IZ m); trivial with sets.
rewrite (addZ_commutativity IZ m); trivial with sets.
Qed.

Lemma tech_opp_pos_negZ1 : forall n : nat, oppZ (pos n) = neg n.
Proof.
intro n; elim n; auto with sets.
Qed.

Lemma tech_opp_pos_negZ2 : forall n : nat, oppZ (neg n) = pos n.
Proof.
intro n; elim n; auto with sets.
Qed.

Theorem change_exponent_sign :
 forall (a : U) (m : Z), In U G a -> inv (exp m a) = exp (oppZ m) a.
Proof.
intros a m; elim m.
simpl in |- *; auto with sets.
simpl in |- *; auto with sets.
intro H'; symmetry  in |- *; auto with sets.
intros n H'.
rewrite (tech_opp_pos_negZ1 n).
elim n; auto with sets.
intros n0 H'0.
rewrite (exp_unfold_pos a n0); trivial with sets.
rewrite (exp_unfold_neg a n0); trivial with sets.
rewrite <- (exp_commut1 a (pos n0)); trivial with sets.
rewrite <- (inv_star' (exp (pos n0) a) a); auto with sets.
rewrite H'0; trivial with sets.
intros n H'.
rewrite (tech_opp_pos_negZ2 n).
elim n.
simpl in |- *; symmetry  in |- *; auto with sets.
intros n0 H'0.
rewrite (exp_unfold_pos a n0); trivial with sets.
rewrite (exp_unfold_neg a n0); trivial with sets.
rewrite <- (exp_commut1 a (pos n0)); trivial with sets.
rewrite <- (inv_star' (inv a) (exp (neg n0) a)); auto with sets.
rewrite H'0; trivial with sets.
rewrite <- (inv_involution' a); trivial with sets.
Qed.

Inductive powers (a : U) : Ensemble U :=
    In_powers : forall (m : Z) (x : U), x = exp m a -> In U (powers a) x.

Theorem powers_of_one_element :
 forall a : U, In U G a -> Setsubgroup U (powers a) Gr.
Proof.
intros a H'.
apply T_1_6_2 with (witness := a).
apply In_powers with (m := IZ); auto with sets.
red in |- *.
intros x H'0; elim H'0.
intros m x0 H'1; rewrite H'1; auto with sets.
red in |- *.
intros x y H'0; elim H'0.
intros m x0 H'1 H'2; elim H'2.
intros m0 x1 H'3; rewrite H'3.
rewrite H'1.
rewrite (add_exponents a m m0); trivial with sets.
apply In_powers with (m := addZ m m0); trivial with sets.
red in |- *.
intros x H'0; elim H'0.
intros m x0 H'1.
apply In_powers with (m := oppZ m); trivial with sets.
rewrite H'1.
apply change_exponent_sign; trivial with sets.
Qed.

Section Second.

Variable H : Ensemble U.
Variable witness : U.
Variable h0 : In U H witness.
Variable h1 : Included U H G.
Variable h2 : forall a b : U, In U H a -> In U H b -> In U H (star a (inv b)).

Let eH : U := star witness (inv witness).

Theorem T_1_6_3 : Setsubgroup U H Gr.
Proof.
cut (In U H eH).
intro H'.
apply T_1_6_2 with (witness := witness); auto with sets.
red in |- *; intros a b H'0 H'1; try assumption.
lapply (h2 eH b);
 [ intro H'4; lapply H'4; [ intro H'5; try exact H'5; clear H'4 | clear H'4 ]
 | idtac ]; auto with sets.
unfold eH at 1 in H'5.
generalize H'5; clear H'5.
rewrite (G3b' witness).
rewrite (G2b' (inv b)).
intro H'4.
lapply (h2 a (inv b));
 [ intro H'5; lapply H'5;
    [ intro H'6; generalize H'6; clear H'5 | clear H'5 ]
 | idtac ]; auto with sets.
rewrite <- (inv_involution' b); auto with sets.
red in |- *; intros a H'0; try assumption.
rewrite <- (G2b' (inv a)).
apply h2; auto with sets.
unfold eH at 1 in H'.
rewrite <- (G3b' witness); auto with sets.
unfold eH at 1 in |- *; auto with sets.
Qed.

End Second.

Theorem Ex1 : Setsubgroup U (Singleton U e) Gr.
Proof.
apply T_1_6_2 with (witness := e); auto with sets.
red in |- *; intros x H'; elim H'; auto with sets.
red in |- *; intros a b H' H'0.
elim H'.
elim H'0.
rewrite (G2c' e); auto with sets.
red in |- *; intros a H'; elim H'.
rewrite <- (resolve' e e); auto with sets.
Qed.

Theorem Ex2 : Setsubgroup U (Singleton U e) Gr.
Proof.
apply T_1_6_3 with (witness := e); auto with sets.
red in |- *.
intros x H'; elim H'; auto with sets.
intros a b H'; elim H'.
intro H'0; elim H'0.
rewrite (G3b' e); auto with sets.
Qed.

Lemma Ex3 : forall n : Z, exp n e = e.
Proof.
intro n; elim n; auto with sets.
intro n0; elim n0; auto with sets.
intros n1 H'.
rewrite (exp_unfold_pos e n1); auto with sets.
rewrite H'; auto with sets.
intro n0; elim n0; auto with sets.
simpl in |- *.
symmetry  in |- *; auto with sets.
intros n1 H'.
rewrite (exp_unfold_neg e n1); auto with sets.
rewrite H'; auto with sets.
Qed.

Lemma Ex4 : powers e = Singleton U e.
Proof.
apply Extensionality_Ensembles; split; red in |- *; auto with sets.
intros x H'; elim H'.
intros m x0 H'0; rewrite H'0.
rewrite (Ex3 m); auto with sets.
intros x H'; elim H'.
apply In_powers with (m := IZ); auto with sets.
Qed.

Theorem Ex5 : Setsubgroup U (Singleton U e) Gr.
Proof.
rewrite <- Ex4.
apply powers_of_one_element; auto with sets.
Qed.


(** * Tactics: More Basic Tactics *)

(** This chapter introduces several additional proof strategies
    and tactics that allow us to begin proving more interesting
    properties of functional programs.

    We will see:
    - how to use auxiliary lemmas in both "forward-" and
      "backward-style" proofs;
    - how to reason about data constructors -- in particular, how to
      use the fact that they are injective and disjoint;
    - how to strengthen an induction hypothesis, and when such
      strengthening is required; and
    - more details on how to reason by case analysis. *)

Set Warnings "-notation-overridden,-parsing".
From LF Require Export Poly.

(* ################################################################# *)
(** * 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 : nat),
     n = m ->
     n = m.
Proof.
  intros n m eq.

(** Here, we could finish with "[rewrite -> eq.  reflexivity.]" as we
    have done several times before.  Alternatively, we can finish in
    a single step by using the [apply] tactic: *)

  apply eq.  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 ->
    (n = m -> o = p) ->
    o = p.
Proof.
  intros n m o p eq1 eq2.
  apply eq2. apply eq1.  Qed.

(** Typically, when we use [apply H], the statement [H] will
    begin with a [forall] that introduces some _universally quantified
    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, standard, optional (silly_ex)

    Complete the following proof using only [intros] and [apply]. *)

Theorem silly_ex : forall p,
     (forall n, evenb n = true -> evenb (S n) = false) ->
     (forall n, evenb n = false -> oddb n = true) ->
     evenb p = true ->
     oddb (S p) = true.
Proof.
  intros p H H1 evenp.
  apply H1. apply H. apply evenp.
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 : forall (n m : nat),
     n = m ->
     m = n.
Proof.
  intros n m H.

  (** Here we cannot use [apply] directly... *)

  Fail apply H.

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

  symmetry. apply H.  Qed.

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

    _Hint_: You can also use [apply] with previously defined lemmas,
    not just hypotheses in the context.  You may find earlier lemmas
    like [app_nil_r], [app_assoc], [rev_app_distr], [rev_involutive],
    etc. helpful.  Also, remember that [Search] is your friend (though
    it may not find earlier lemmas if they were posed as optional
    problems and you chose not to finish the proofs). *)

Search "rev" inside Poly.
Search "rev" inside Lists.

Theorem rev_exercise1 : forall (l l' : list nat),
     l = rev l' ->
     l' = rev l.
Proof.
  intros l l' eq.
  rewrite <- rev_involutive.
  rewrite -> eq.
  rewrite -> rev_involutive.
  rewrite -> rev_involutive.
  reflexivity.
Qed.

(** [] *)

(** **** Exercise: 1 star, standard, optional (apply_rewrite)

    Briefly explain the difference between the tactics [apply] and
    [rewrite].  What are the situations where both can usefully be
    applied? *)

(* H: a <=> b  rewrite works
   H: a -> b   when goal is b, apply H works; when goal is a, apply H does not work.

    [] *)

(* ################################################################# *)
(** * 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 like to pull it out as a
    lemma that records, 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, the name [m] in the [with] clause is not required,
    since Coq is often smart enough to figure out which variable we
    are instantiating. We could instead simply write [apply trans_eq
    with [c;d]]. *)

(** Coq also has a built-in tactic [transitivity] that
    accomplishes the same purpose as applying [trans_eq]. The tactic
    requires us to state the instantiation we want, just like [apply
    with] does. *)

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.
  transitivity [c;d].
  apply eq1. apply eq2.   Qed.

(** **** Exercise: 3 stars, standard, optional (trans_eq_exercise) *)
Example trans_eq_exercise : forall (n m o p : nat),
     m = (minustwo o) ->
     (n + p) = m ->
     (n + p) = (minustwo o).
Proof.
  intros n m o p eq1 eq2.
  transitivity m.
  - apply eq2.
  - apply eq1.
Qed.
(** [] *)

(* ################################################################# *)
(** * The [injection] and [discriminate] Tactics *)

(** Recall the definition of natural numbers:

     Inductive nat : Type :=
       | O
       | S (n : nat).

    It is obvious 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 are two
    additional facts:

    - The constructor [S] is _injective_ (or _one-to-one_).  That is,
      if [S n = S m], it must be that [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 every inductively defined type:
    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 different.  (Since [true] and
    [false] take no arguments, their injectivity is neither here nor
    there.)  And so on. *)

(** We can _prove_ the injectivity of [S] by using the [pred] function
    defined in [Basics.v]. *)

Theorem S_injective : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H1.
  assert (H2: n = pred (S n)). { reflexivity. }
  rewrite H2. rewrite H1. simpl. reflexivity.
Qed.

(** This technique can be generalized to any constructor by
    writing the equivalent of [pred] -- i.e., writing a function that
    "undoes" one application of the constructor.

    As a more convenient alternative, Coq provides a tactic called
    [injection] that allows us to exploit the injectivity of any
    constructor.  Here is an alternate proof of the above theorem
    using [injection]: *)

Theorem S_injective' : forall (n m : nat),
  S n = S m ->
  n = m.
Proof.
  intros n m H.

(** By writing [injection H as Hmn] at this point, we are asking Coq
    to generate all equations that it can infer from [H] using the
    injectivity of constructors (in the present example, the equation
    [n = m]). Each such equation is added as a hypothesis (with the
    name [Hmn] in this case) into the context. *)

  injection H as Hnm. apply Hnm.
Qed.

(** Here's a more interesting example that shows how [injection] can
    derive multiple equations at once. *)

Theorem injection_ex1 : forall (n m o : nat),
  [n;m] = [o;o] ->
  n = m.
Proof.
  intros n m o H.
  (* WORKED IN CLASS *)
  injection H as H1 H2.
  rewrite H1. rewrite H2. reflexivity.
Qed.

(** Alternatively, if you just say [injection H] with no [as] clause,
    then all the equations will be turned into hypotheses with names
    chosen by Coq. *)

Theorem injection_ex2 : forall (n m o : nat),
  [n; m] = [o; o] ->
  n = m.
Proof.
  intros n m o H.
  injection H.
  (* WORKED IN CLASS *)
  intros H1 H2. rewrite H1. rewrite H2. reflexivity.
Qed.

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

Lemma injection_ex3_lemma : forall (X: Type) (x y:X) (l: list X), x :: l = y :: l -> x = y.
Proof.
  intros X x y l eq.
  injection eq as H.
  apply H.
Qed.

Example injection_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  j = z :: l ->
  x = y.
Proof.
  intros X x y z l j eq1 eq2.
  injection eq1 as H1 H2.
  transitivity z.
  - apply H1.
  - apply injection_ex3_lemma with l.
    transitivity j.
    * symmetry. apply eq2.
    * symmetry. apply H2.
Qed.
(** [] *)

(** So much for injectivity of constructors.  What about disjointness?

    The principle of disjointness says that two terms beginning with
    different constructors (like [O] and [S], or [true] and [false])
    can never be equal.  This means that, any time we find ourselves
    in a context where we've _assumed_ that two such terms are equal,
    we are justified in concluding anything we want, since the
    assumption is nonsensical. *)

(** The [discriminate] tactic embodies this principle: It is used on a
    hypothesis involving an equality between different
    constructors (e.g., [false = true]), and it solves the current
    goal immediately.  Some examples: *)

Theorem discriminate_ex1 : forall (n m : nat),
  false = true ->
  n = m.
Proof.
  intros n m contra. discriminate contra. Qed.

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

(** These examples are instances of a logical principle known as the
    _principle of explosion_, which asserts that a contradictory
    hypothesis entails anything (even manifestly false things!). *)

(** If you find the principle of explosion confusing, remember
    that these proofs are _not_ showing that the conclusion of the
    statement holds.  Rather, they are showing that, _if_ the
    nonsensical situation described by the premise did somehow arise,
    _then_ the nonsensical conclusion would also follow, because we'd
    be living in an inconsistent universe where every statement is
    true.  We'll explore the principle of explosion in more detail in
    the next chapter. *)

(** **** Exercise: 1 star, standard (discriminate_ex3) *)
Example discriminate_ex3 :
  forall (X : Type) (x y z : X) (l j : list X),
    x :: y :: l = [] ->
    x = z.
Proof.
  intros X x y z l j contra.
  discriminate contra. Qed.
(** [] *)

(** For a slightly more involved example, we can use [discriminate] to
    make a connection between the two different notions of
    equality ([=] and [=?]) on natural numbers. *)
Theorem eqb_0_l : forall n,
   0 =? n = true -> n = 0.
Proof.
  intros n.

(** We can proceed by case analysis on [n]. The first case is
    trivial. *)

  destruct n as [| n'] eqn:E.
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming [0
    =? (S n') = true], we must show [S n' = 0]!  The way forward is to
    observe that the assumption itself is nonsensical: *)

  - (* n = S n' *)
    simpl.

(** If we use [discriminate] on this hypothesis, Coq confirms
    that the subgoal we are working on is impossible and removes it
    from further consideration. *)

    intros H. discriminate H.
Qed.

(** The injectivity of constructors allows us to reason that
    [forall (n m : nat), S n = S m -> n = m].  The converse of this
    implication is an instance of a more general fact about both
    constructors and functions, which we will find convenient in a few
    places below: *)

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.

Theorem eq_implies_succ_equal : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. apply f_equal. apply H. Qed.

(** There is also a tactic named `f_equal` that can prove such
    theorems.  Given a goal of the form [f a1 ... an = g b1 ... bn],
    the tactic [f_equal] will produce subgoals of the form [f = g],
    [a1 = b1], ..., [an = bn]. At the same time, any of these subgoals
    that are simple enough (e.g., immediately provable by
    [reflexivity]) will be automatically discharged by [f_equal]. *)

Theorem eq_implies_succ_equal' : forall (n m : nat),
    n = m -> S n = S m.
Proof. intros n m H. f_equal. apply H. Qed.

(* ################################################################# *)
(** * 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 on
    the hypothesis [H] in the context. *)

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

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

    In other words, [apply L in H] gives us a form of "forward
    reasoning": given [X -> Y] and a hypothesis matching [X], it
    produces a hypothesis matching [Y].

    By contrast, [apply L] is "backward reasoning": it says that if we
    know [X -> Y] and we are trying to prove [Y], it suffices to prove
    [X].

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

Theorem silly4 : forall (n m p q : nat),
  (n = m -> p = q) ->
  m = n ->
  q = p.
Proof.
  intros n m p q 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.

    The informal proofs that you've seen in math or computer science
    classes probably tended to use forward reasoning.  In general,
    idiomatic use of Coq favors backward reasoning, but in some
    situations the forward style can be easier to think about. *)

(* ################################################################# *)
(** * 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 sometimes 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 [double] is injective -- i.e., that it 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 bit delicate: if we begin it with

       intros n. induction n.

    all is well.  But if we begin it with introducing both variables

       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' IHn'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *) reflexivity.
    + (* m = S m' *) discriminate eq.
  - (* n = S n' *) intros eq. destruct m as [| m'] eqn:E.
    + (* m = O *) discriminate eq.
    + (* m = S m' *) apply f_equal.

(** At this point, 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 _these 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, for
    _all_ [n], that the proposition

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

    holds, by showing

      - [P O]

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

      - [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: 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 (arbitrary,
    but fixed) [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 at all with proving
    [R]!  If we tried to prove [R] from [Q], we would start with
    something like "Suppose [double (S n) = 10]..." but then we'd be
    stuck: knowing that [double (S n)] is [10] tells us nothing
    helpful about whether [double n] is [10] (indeed, it strongly
    suggests that [double n] is _not_ [10]!!), so [Q] is useless. *)

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

(** A successful proof of [double_injective] leaves [m] universally
    quantified 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' IHn'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'] eqn:E.
    + (* m = O *) reflexivity.
    + (* m = S m' *) discriminate eq.

  - (* n = S n' *)

(** Notice that both the goal and the induction hypothesis are
    different this time: the goal asks us to prove something more
    general (i.e., we must 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've chosen a particular [m] and introduced the assumption
    that [double n = double m].  Since we are doing a case analysis on
    [n], we also need a case analysis on [m] to keep the two "in sync." *)

    destruct m as [| m'] eqn:E.
    + (* m = O *)

(** The 0 case is trivial: *)

    discriminate eq.
    + (* 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 is the predecessor of the
    [m] 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 current [m'] (this instantiation is
    performed automatically by the [apply] in the next step), then
    [IHn'] gives us exactly what we need to finish the proof. *)

      apply IHn'. simpl in eq. injection eq as goal. apply goal. Qed.

(** What you should take away from all this is that you need to be
    careful, when using induction, that you are not trying to prove
    something too specific: When proving a property involving two
    variables [n] and [m] by induction on [n], it is sometimes crucial
    to leave [m] generic. *)

(** The following exercise (which further strengthens the link between
    [=?] and [=]) follows the same pattern. *)

(** **** Exercise: 2 stars, standard (eqb_true) *)
Theorem eqb_true : forall n m,
    n =? m = true -> n = m.
Proof.
  induction n as [| n' IHn'].
  - simpl. destruct m as [| m'] eqn:E.
    * reflexivity.
    * intros H. discriminate H.
  - simpl. destruct m as [| m'] eqn:E.
    * intros H. discriminate H.
    * intros H. f_equal. apply IHn'. apply H.
Qed.
(** [] *)

(** **** Exercise: 2 stars, advanced (eqb_true_informal)

    Give a careful informal proof of [eqb_true], being as explicit
    as possible about quantifiers. *)

(* FILL IN HERE *)

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

(** **** Exercise: 3 stars, standard, especially useful (plus_n_n_injective)

    In addition to being careful about how you use [intros], practice
    using "in" variants in this proof.  (Hint: use [plus_n_Sm].) *)
Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  induction n as [| n' IHn'].
  - intros m. destruct m.
    * reflexivity.
    * intros H. discriminate H.
  - intros m. simpl. rewrite <- plus_n_Sm. destruct m.
    * intros H. discriminate H.
    * intros H. f_equal. apply IHn'.
      simpl in H. rewrite <- plus_n_Sm in H. injection H as H1.
      apply H1.
Qed.

(** [] *)

(** The strategy of doing fewer [intros] before an [induction] to
    obtain a more general IH doesn't always work by itself; sometimes
    some _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' IHm'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
        (* We are stuck here, just like before. *)
Abort.

(** The problem is that, to do induction on [m], we must first
    introduce [n].  (And 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
    works, but it's not nice: We don't want to have to twist the
    statements of lemmas to fit the needs of a particular strategy for
    proving them!  Rather we want to state them in the clearest and
    most natural way. *)

(** What we can do instead is to first introduce all the quantified
    variables and then _re-generalize_ one or more of them,
    selectively taking variables 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' IHm'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) reflexivity.
    + (* n = S n' *) discriminate eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'] eqn:E.
    + (* n = O *) discriminate eq.
    + (* n = S n' *) apply f_equal.
      apply IHm'. injection eq as goal. apply goal. 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 [m = 0 = n], as required.  Otherwise, if [n = S n']
        for some [n'], we derive a contradiction: by the definition of
        [double], we can calculate [double n = S (S (double n'))], but
        this contradicts the assumption that [double n = 0].

      - Second, 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 injectivity 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. [] *)

(** **** Exercise: 3 stars, standard, especially useful (gen_dep_practice)

    Prove this by induction on [l]. *)

Theorem nth_error_after_last: forall (n : nat) (X : Type) (l : list X),
     length l = n ->
     nth_error l n = None.
Proof.
  intros n X l.
  generalize dependent n.
  induction l as [| n l' IHl'].
  - destruct n.
    * reflexivity.
    * intros H. discriminate H.
  - destruct n0.
    * simpl. intros H. discriminate H.
    * simpl. intros H. apply IHl'. injection H as goal. apply goal.
Qed.
(** [] *)

(* ################################################################# *)
(** * Unfolding Definitions *)

(** It sometimes happens that we need to manually unfold a name that
    has been introduced by a [Definition] so that we can manipulate
    the expression it denotes.  For example, if we define... *)

Definition square n := n * n.

(** ... and try to prove a simple fact about [square]... *)

Lemma square_mult : forall n m, square (n * m) = square n * square m.
Proof.
  intros n m.
  simpl.

(** ... we appear to be stuck: [simpl] doesn't simplify anything, and
    since we haven't proved any other facts about [square], there is
    nothing we can [apply] or [rewrite] with. *)

(** To make progress, we can manually [unfold] the definition of
    [square]: *)

  unfold square.

(** Now we have plenty to work with: both sides of the equality are
    expressions involving multiplication, and we have lots of facts
    about multiplication at our disposal.  In particular, we know that
    it is commutative and associative, and from these it is not hard
    to finish the proof. *)

  rewrite mult_assoc.
  assert (H : n * m * n = n * n * m).
    { rewrite mult_comm. apply mult_assoc. }
  rewrite H. rewrite mult_assoc. reflexivity.
Qed.

(** At this point, some deeper discussion of unfolding and
    simplification is in order.

    We already have observed that tactics like [simpl], [reflexivity],
    and [apply] will often unfold the definitions of functions
    automatically when this allows them to make progress.  For
    example, if we define [foo m] to be the constant [5]... *)

Definition foo (x: nat) := 5.

(** .... then the [simpl] in the following proof (or the
    [reflexivity], if we omit the [simpl]) will unfold [foo m] to
    [(fun x => 5) m] and then further simplify this expression to just
    [5]. *)

Fact silly_fact_1 : forall m, foo m + 1 = foo (m + 1) + 1.
Proof.
  intros m.
  simpl.
  reflexivity.
Qed.

(** But this automatic unfolding is somewhat conservative.  For
    example, if we define a slightly more complicated function
    involving a pattern match... *)

Definition bar x :=
  match x with
  | O => 5
  | S _ => 5
  end.

(** ...then the analogous proof will get stuck: *)

Fact silly_fact_2_FAILED : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  simpl. (* Does nothing! *)
Abort.

(** The reason that [simpl] doesn't make progress here is that it
    notices that, after tentatively unfolding [bar m], it is left with
    a match whose scrutinee, [m], is a variable, so the [match] cannot
    be simplified further.  It is not smart enough to notice that the
    two branches of the [match] are identical, so it gives up on
    unfolding [bar m] and leaves it alone.  Similarly, tentatively
    unfolding [bar (m+1)] leaves a [match] whose scrutinee is a
    function application (that cannot itself be simplified, even
    after unfolding the definition of [+]), so [simpl] leaves it
    alone. *)

(** At this point, there are two ways to make progress.  One is to use
    [destruct m] to break the proof into two cases, each focusing on a
    more concrete choice of [m] ([O] vs [S _]).  In each case, the
    [match] inside of [bar] can now make progress, and the proof is
    easy to complete. *)

Fact silly_fact_2 : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  destruct m eqn:E.
  - simpl. reflexivity.
  - simpl. reflexivity.
Qed.

(** This approach works, but it depends on our recognizing that the
    [match] hidden inside [bar] is what was preventing us from making
    progress. *)

(** A more straightforward way forward is to explicitly tell Coq to
    unfold [bar]. *)

Fact silly_fact_2' : forall m, bar m + 1 = bar (m + 1) + 1.
Proof.
  intros m.
  unfold bar.

(** Now it is apparent that we are stuck on the [match] expressions on
    both sides of the [=], and we can use [destruct] to finish the
    proof without thinking too hard. *)

  destruct m eqn:E.
  - reflexivity.
  - reflexivity.
Qed.

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

(** We have seen many examples where [destruct] is used to
    perform case analysis of the value of some variable.  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 n =? 3 then false
  else if n =? 5 then false
  else false.

Theorem sillyfun_false : forall (n : nat),
  sillyfun n = false.
Proof.
  intros n. unfold sillyfun.
  destruct (n =? 3) eqn:E1.
    - (* n =? 3 = true *) reflexivity.
    - (* n =? 3 = false *) destruct (n =? 5) eqn:E2.
      + (* n =? 5 = true *) reflexivity.
      + (* n =? 5 = false *) reflexivity.  Qed.

(** After unfolding [sillyfun] in the above proof, we find that
    we are stuck on [if (n =? 3) then ... else ...].  But either
    [n] is equal to [3] or it isn't, so we can use [destruct (eqb
    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: 3 stars, standard (combine_split)

    Here is an implementation of the [split] function mentioned in
    chapter [Poly]: *)

Fixpoint split {X Y : Type} (l : list (X*Y))
               : (list X) * (list Y) :=
  match l with
  | [] => ([], [])
  | (x, y) :: t =>
      match split t with
      | (lx, ly) => (x :: lx, y :: ly)
      end
  end.

(** Prove that [split] and [combine] are inverses in the following
    sense: *)
Print combine.

Theorem combine_split : forall X Y (l : list (X * Y)) l1 l2,
  split l = (l1, l2) ->
  combine l1 l2 = l.
Proof.
  intros X Y l.
  induction l as [| n l' IHl'].
  - intros l1 l2 H. injection H as H1 H2. rewrite <- H1. rewrite <- H2. reflexivity.
  - simpl. intros l1 l2 H. destruct n. destruct (split l').
    injection H as H1 H2.
    rewrite <- H1. rewrite <- H2.
    simpl. f_equal. apply IHl'. reflexivity.
Qed.

(** [] *)

(** The [eqn:] part of the [destruct] tactic is optional; though we've
    chosen to include it most of the time, for the sake of
    documentation, but it can often be omitted without harm.

    However, when [destruct]ing compound expressions, the information
    recorded by the [eqn:] can actually be critical: if we leave it
    out, then [destruct] can erase information we need to complete a
    proof.

    For example, suppose we define a function [sillyfun1] like
    this: *)

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

(** Now suppose that we want to convince Coq that [sillyfun1 n]
    yields [true] only when [n] is odd.  If we start the proof like
    this (with no [eqn:] on the [destruct])... *)

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

(** ... then we are stuck at this point because the context does
    not contain enough information to prove the goal!  The problem is
    that the substitution performed by [destruct] is quite brutal --
    in this case, it throws away every occurrence of [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 [n =?
    3 = true] in this branch of the case analysis, it must be that [n
    = 3], from which it follows that [n] is odd.

    What we want here is to substitute away all existing occurences of
    [n =? 3], but at the same time add an equation to the context that
    records which case we are in.  This is precisely what the [eqn:]
    qualifier does. *)

Theorem sillyfun1_odd : forall (n : nat),
     sillyfun1 n = true ->
     oddb n = true.
Proof.
  intros n eq. unfold sillyfun1 in eq.
  destruct (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. *)
    - (* e3 = true *) apply eqb_true in Heqe3.
      rewrite -> Heqe3. reflexivity.
    - (* 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, allowing us to finish the
        proof. *)
      destruct (n =? 5) eqn:Heqe5.
        + (* e5 = true *)
          apply eqb_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* e5 = false *) discriminate eq.  Qed.

(** **** Exercise: 2 stars, standard (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 eqn:Hb.
  - destruct (f true) eqn:ft.
    * rewrite -> ft. apply ft.
    * destruct (f false) eqn:ff.
      + apply ft.
      + apply ff.
  - destruct (f false) eqn:ff.
    * destruct (f true) eqn:ft.
      + apply ft.
      + apply ff.
    * rewrite -> ff. apply ff.
Qed.
(** [] *)

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

(** We've now seen many of Coq's most fundamental tactics.  We'll
    introduce a few more in the coming chapters, and later on we'll
    see some more powerful _automation_ tactics that make Coq help us
    with low-level details.  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]

      - [transitivity y]: prove a goal [x=z] by proving two new subgoals,
        [x=y] and [y=z]

      - [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

      - [injection]: reason by injectivity on equalities
        between values of inductively defined types

      - [discriminate]: reason by disjointness of constructors on
        equalities between values of inductively defined types

      - [assert (H: e)] (or [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

      - [f_equal]: change a goal of the form [f x = f y] into [x = y] *)

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

(** **** Exercise: 3 stars, standard (eqb_sym) *)
Theorem eqb_sym : forall (n m : nat),
  (n =? m) = (m =? n).
Proof.
  induction n as [| n' IHn'].
  - destruct m.
    * reflexivity.
    * simpl. reflexivity.
  - destruct m.
    * simpl. reflexivity.
    * simpl. apply IHn'.
Qed.

(** [] *)

(** **** Exercise: 3 stars, advanced, optional (eqb_sym_informal)

    Give an informal proof of this lemma that corresponds to your
    formal proof above:

   Theorem: For any [nat]s [n] [m], [(n =? m) = (m =? n)].

   Proof: *)
   (* FILL IN HERE

    [] *)

(** **** Exercise: 3 stars, standard, optional (eqb_trans) *)
Theorem eqb_trans : forall n m p,
  n =? m = true ->
  m =? p = true ->
  n =? p = true.
Proof.
  intros n m p nm mp. Search (?x =? ?y = true).
  apply eqb_true in nm. apply eqb_true in mp.
  rewrite <- mp. rewrite <- nm. rewrite <- eqb_refl. reflexivity.
Qed.
(** [] *)

(** **** Exercise: 3 stars, advanced (split_combine)

    We proved, in an exercise above, 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 :=
  forall X Y (l1:list X) (l2:list Y),
  length l1 = length l2 -> split (combine l1 l2) = (l1, l2).

Theorem split_combine : split_combine_statement.
Proof.
  intros X Y l1.
  induction l1 as [| h l1' IHl1'].
  - intros l2 H. destruct l2.
    + reflexivity.
    + simpl in H. discriminate H.
  -  intros l2 H. simpl in H. destruct l2.
    + discriminate H.
    + simpl in H. injection H as H1. apply IHl1' in H1.
      simpl. rewrite -> H1. reflexivity.
Qed.

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

(** **** Exercise: 3 stars, advanced (filter_exercise)

    This one is a bit challenging.  Pay attention to the form of your
    induction hypothesis. *)

Theorem filter_exercise : forall (X : Type) (test : X -> bool)
                             (x : X) (l lf : list X),
     filter test l = x :: lf ->
     test x = true.
Proof.
  intros X p x. induction l as [| h l' IHl'].
  - intros. simpl in H. discriminate H.
  - intros lf. simpl. destruct (p h) eqn:ph.
    + intros H. injection H as H1 H2.
      rewrite -> H1 in ph. apply ph.
    + intros H. apply IHl' in H. apply H.
Qed.

(** [] *)

(** **** Exercise: 4 stars, advanced, especially useful (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 (eqb 5) [] = true

    The second checks whether there exists an element in the list that
    satisfies a given predicate:

      existsb (eqb 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].

    Finally, prove a theorem [existsb_existsb'] stating that
    [existsb'] and [existsb] have the same behavior.
*)

Check fold.
Fixpoint forallb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | nil => true
  | h :: t => if test h then forallb test t else false
  end.

Example test_forallb_1 : forallb oddb [1;3;5;7;9] = true.
Proof. reflexivity. Qed.

Example test_forallb_2 : forallb negb [false;false] = true.
Proof. reflexivity. Qed.

Example test_forallb_3 : forallb evenb [0;2;4;5] = false.
Proof. reflexivity. Qed.

Example test_forallb_4 : forallb (eqb 5) [] = true.
Proof. reflexivity. Qed.

Fixpoint existsb {X : Type} (test : X -> bool) (l : list X) : bool :=
  match l with
  | nil => false
  | h :: t => if test h then true else existsb test t
  end.

Example test_existsb_1 : existsb (eqb 5) [0;2;3;6] = false.
Proof. reflexivity. Qed.

Example test_existsb_2 : existsb (andb true) [true;true;false] = true.
Proof. reflexivity. Qed.

Example test_existsb_3 : existsb oddb [1;0;0;0;0;3] = true.
Proof. reflexivity. Qed.

Example test_existsb_4 : existsb evenb [] = false.
Proof. reflexivity. Qed.

Definition existsb' {X : Type} (test : X -> bool) (l : list X) : bool :=
  negb (forallb (fun x => negb (test x)) l).

Theorem existsb_existsb' : forall (X : Type) (test : X -> bool) (l : list X),
  existsb test l = existsb' test l.
Proof.
  intros X p. induction l as [| h l' IHl'].
  - reflexivity.
  - destruct (p h) eqn:ph.
    + simpl. rewrite -> ph. unfold existsb'. simpl. rewrite -> ph. reflexivity.
    + simpl. rewrite -> ph. unfold existsb'. simpl. rewrite -> ph. simpl. rewrite -> IHl'. reflexivity.
Qed.

(** [] *)

(* 2020-10-01 08:07 *)