From Coq Require Import Bool Setoid List NArith.
From Coq Require ListSet.
From Coq Require Import FSets.FSetAVL FSetFacts.
From Coq Require String.

Require Import ListSet2 StringCmp.

(** A finite set class.
    These axioms require convertibility to lists.
    (see theories/Lists/ListSet.v from a Coq distribution).
    See theories/MSet/MSetInterface.v for a module-based interface.
 *)
Class class {M: Type} (E: forall x y: M, {x = y} + {x <> y}) (S: Type) := {
  (** Convert a set to a list. The order may be arbitrary. *)
  to_list: S -> list M;
  (** A list produced by set_to_list may only include each element once. *)
  to_list_nodup (s: S): NoDup (to_list s);
  (** Build a set from a list. The list may contain duplicates. *)
  from_list: list M -> S;

  (** Membership test. *)
  has: S -> M -> bool;

  (** [has] may be computed from [to_list]. *)
  has_to_list (x: M) (s: S):
    has s x = ListSet.set_mem E x (to_list s);

  (** A set obtained from [from_list] has the same members as the list. *)
  has_from_list (x: M) (l: list M):
    has (from_list l) x = ListSet.set_mem E x l;

  (** An empty set. Could work faster than [from_list nil].
      Note that there may be different empty sets even though they are all equivalent.
      In particular, it might happen that that [empty <> from_list nil].
   *)
  empty: S;
  empty_to_list: to_list empty = nil;

  (** A set with a single element. Could work faster than [set_from_list (x :: nil)]. *)
  singleton: M -> S;
  singleton_to_list (x: M): to_list (singleton x) = x :: nil;

  (** The number of elements in a set. Could work faster than [length (set_to_list s)]. *)
  size_nat: S -> nat;
  size_nat_to_list (s: S): size_nat s = length (to_list s);

  (** A test for empty set. Could work faster than [set_size_nat =? 0]. *)
  is_empty: S -> bool;
  is_empty_to_list (s: S): is_empty s = true <-> to_list s = nil;

  (** The number of elements in a set, the version with N.
      Could work faster than [N_of_nat (set_size_nat _)].
   *)
  size: S -> N;
  size_ok (s: S): size s = N_of_nat (size_nat s);

  (** Add an item to a set. *)
  add: S -> M -> S;
  add_ok (s: S) (x: M) (y: M):
    has (add s x) y = if E x y then true else has s y;

  (** Remove an item from a set. *)
  remove: S -> M -> S;
  remove_ok (s: S) (x: M) (y: M):
    has (remove s x) y = if E x y then false else has s y;

  union: S -> S -> S;
  union_ok (a b: S):
    forall x: M,
      has (union a b) x
       =
      orb (has a x) (has b x);
  inter: S -> S -> S;
  inter_ok (a b: S):
    forall x: M,
      has (inter a b) x
       =
      andb (has a x) (has b x);
  diff: S -> S -> S;
  diff_ok (a b: S):
    forall x: M,
      has (diff a b) x
       =
      andb (has a x) (negb (has b x));

  for_all: S -> (M -> bool) -> bool;
  for_all_ok (s: S) (p: M -> bool):
    for_all s p = true
     <->
    forall x: M,
      has s x = true -> p x = true;

  (** A test for being a subset. *)
  is_subset: S -> S -> bool;
  is_subset_ok (little big: S):
    is_subset little big = true
     <->
    forall x: M,
      orb (negb (has little x)) (has big x) = true;

  (** A test for set equality.
      Note that two set_eq sets may not be equal in the sense of Coq's equality,
      for example: when lists are used as sets, [0, 1] and [1, 0] are set_eq but not eq.
    *)
  equal: S -> S -> bool;
  equal_ok (a b: S):
    equal a b = true
     <->
    forall x: M,
      has a x = has b x;
}.

Definition lists_as_sets {M: Type} (E: forall x y: M, {x = y} + {x <> y})
: class E {l: list M | NoDup l}
:= {|
      to_list s := proj1_sig s;
      to_list_nodup s := proj2_sig s;
      from_list (l: list M) := exist _ (nodup E l) (NoDup_nodup E l);
      has s x := nodup_list_in E x s;
      has_to_list x l := eq_refl;
      has_from_list := set_mem_nodup E;
      empty := exist _ nil (NoDup_nil M);
      empty_to_list := eq_refl;
      singleton (x: M) := exist _ (x :: nil) (NoDup_cons x (@in_nil _ x) (NoDup_nil M));
      singleton_to_list (x: M) := eq_refl;
      size_nat s := length (proj1_sig s);
      size_nat_to_list s := eq_refl;
      is_empty s := list_is_empty (proj1_sig s);
      is_empty_to_list s := list_is_empty_ok (proj1_sig s);
      size s := N.of_nat (length (proj1_sig s));
      size_ok s := eq_refl;
      add s x := nodup_list_add E x s;
      add_ok s x := nodup_list_add_ok E x s;
      remove s x := nodup_list_remove E x s;
      remove_ok s x := nodup_list_remove_ok E x s;
      union := nodup_list_union E;
      union_ok := nodup_list_union_ok E;
      inter := nodup_list_inter E;
      inter_ok := nodup_list_inter_ok E;
      diff := nodup_list_diff E;
      diff_ok := nodup_list_diff_ok E;
      for_all := nodup_list_forall;
      for_all_ok := nodup_list_forall_ok E;
      is_subset := nodup_list_subset E;
      is_subset_ok := nodup_list_subset_ok E;
      equal := nodup_list_set_eq E;
      equal_ok := nodup_list_set_eq_ok E;
   |}.

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

(* A set of strings based on FSetAVL. *)

Module StringAVLSet := FSetAVL.Make StringLexicalOrder.
Definition string_avl_set := StringAVLSet.t.

Lemma ina_in {A} (l: list A) (x: A):
  SetoidList.InA eq x l <-> In x l.
Proof.
induction l; split; intro H; inversion H; subst; clear H; cbn; try tauto.
{ now constructor. }
rewrite<- IHl in *.
now apply SetoidList.InA_cons_tl.
Qed.

Lemma nodupa_nodup {A} (l: list A):
  SetoidList.NoDupA eq l <-> NoDup l.
Proof.
induction l; split; intro H; inversion H; subst; clear H; cbn; try tauto; constructor.
{ rewrite<- ina_in. assumption. }
{ tauto. }
{ rewrite ina_in. assumption. }
{ tauto. }
Qed.

Lemma string_avl_set_to_list_nodup (s: string_avl_set):
  NoDup (StringAVLSet.elements s).
Proof.
rewrite<- nodupa_nodup.
apply StringAVLSet.elements_3w.
Qed.

Lemma string_avl_set_in_to_list x l:
  StringAVLSet.mem x l = ListSet.set_mem String.string_dec x (StringAVLSet.elements l).
Proof.
remember (StringAVLSet.mem x l) as m. destruct m; symmetry in Heqm; symmetry.
{
  rewrite set_mem_true. rewrite<- ina_in.
  apply StringAVLSet.elements_1.
  now apply StringAVLSet.mem_2.
}
rewrite set_mem_false. rewrite<- ina_in.
intro H. apply StringAVLSet.elements_2 in H.
apply StringAVLSet.mem_1 in H.
rewrite Heqm in H. discriminate.
Qed.

Lemma string_avl_set_in_from_list x l:
  StringAVLSet.mem x
    (fold_right StringAVLSet.add StringAVLSet.empty l)
   =
  ListSet.set_mem String.string_dec x l.
Proof.
induction l. { trivial. }
remember (ListSet.set_mem _ _ _) as m.
symmetry in Heqm. destruct m.
{
  apply StringAVLSet.mem_2 in IHl.
  apply set_mem_true in Heqm.
  assert (T: ListSet.set_mem String.string_dec x (a :: l) = true).
  {
    rewrite set_mem_true.
    cbn. now right.
  }
  rewrite T. clear T.
  apply StringAVLSet.mem_1.
  cbn.
  now apply StringAVLSet.add_2.
}
rewrite set_mem_false in Heqm.
match goal with
|- ?lhs = ?rhs => remember lhs as p
end.
cbn.
destruct String.string_dec as [EQ|NE].
{ subst. apply StringAVLSet.mem_1. now apply StringAVLSet.add_1. }
assert (F: p = false).
{
  destruct p; trivial.
  symmetry in Heqp.
  apply StringAVLSet.mem_2 in Heqp.
  cbn in Heqp.
  apply StringAVLSet.add_3 in Heqp.
  {
    apply StringAVLSet.mem_1 in Heqp.
    rewrite<- Heqp. rewrite<- IHl. trivial.
  }
  intro H.
  symmetry in H.
  contradiction.
}
rewrite F. symmetry. now apply set_mem_false.
Qed.

Lemma string_avl_set_empty_to_list s:
  StringAVLSet.is_empty s = true <-> StringAVLSet.elements s = nil.
Proof.
split; intro H.
{
  apply StringAVLSet.is_empty_2 in H.
  unfold StringAVLSet.Empty in H.
  remember (StringAVLSet.elements s) as e.
  destruct e as [| h ]. { trivial. }
  assert (Q: StringAVLSet.In h s).
  {
    apply StringAVLSet.elements_2.
    rewrite ina_in.
    rewrite<- Heqe.
    now constructor.
  }
  exfalso. exact (H h Q).
}
apply StringAVLSet.is_empty_1.
unfold StringAVLSet.Empty.
intros x J. apply StringAVLSet.elements_1 in J. rewrite ina_in in J.
rewrite H in J. cbn in J. exact J.
Qed.

Lemma string_avl_set_add_ok x s y:
  StringAVLSet.mem y (StringAVLSet.add x s)
   =
  if String.string_dec x y then true else StringAVLSet.mem y s.
Proof.
destruct (String.string_dec x y) as [EQ|NE].
{
  apply StringAVLSet.mem_1.
  apply StringAVLSet.add_1.
  assumption.
}
remember (StringAVLSet.mem y s) as y_in.
symmetry in Heqy_in.
destruct y_in.
{
  apply StringAVLSet.mem_2 in Heqy_in.
  apply StringAVLSet.mem_1.
  apply StringAVLSet.add_2.
  assumption.
}
remember (StringAVLSet.mem y (StringAVLSet.add x s)) as f.
symmetry in Heqf. destruct f; trivial.
apply StringAVLSet.mem_2 in Heqf.
assert (J := StringAVLSet.add_3 NE Heqf).
apply StringAVLSet.mem_1 in J.
rewrite<- Heqy_in. rewrite<- J.
trivial.
Qed.

Lemma string_avl_set_remove_ok x s y:
  StringAVLSet.mem y (StringAVLSet.remove x s)
   =
  if String.string_dec x y then false else StringAVLSet.mem y s.
Proof.
destruct (String.string_dec x y) as [EQ|NE].
{
  remember (StringAVLSet.mem y _) as f. symmetry in Heqf. destruct f; trivial.
  apply StringAVLSet.mem_2 in Heqf.
  apply (StringAVLSet.remove_1 EQ) in Heqf.
  contradiction.
}
remember (StringAVLSet.mem y s) as y_in.
symmetry in Heqy_in.
destruct y_in.
{
  apply StringAVLSet.mem_2 in Heqy_in.
  apply StringAVLSet.mem_1.
  exact (StringAVLSet.remove_2 NE Heqy_in).
}
remember (StringAVLSet.mem y (StringAVLSet.remove x s)) as f.
symmetry in Heqf. destruct f; trivial.
apply StringAVLSet.mem_2 in Heqf.
assert (J := StringAVLSet.remove_3 Heqf).
apply StringAVLSet.mem_1 in J.
rewrite<- Heqy_in. rewrite<- J.
trivial.
Qed.

Lemma string_avl_set_union_ok a b x:
  StringAVLSet.mem x (StringAVLSet.union a b) = StringAVLSet.mem x a || StringAVLSet.mem x b.
Proof.
remember (StringAVLSet.mem x (StringAVLSet.union a b)) as in_ab.
remember (StringAVLSet.mem x a) as in_a.
remember (StringAVLSet.mem x b) as in_b.
symmetry in Heqin_ab. symmetry in Heqin_a. symmetry in Heqin_b.
destruct in_ab; destruct in_a; destruct in_b; cbn; trivial; exfalso;
  try apply StringAVLSet.mem_2 in Heqin_ab;
  try apply StringAVLSet.mem_2 in Heqin_a;
  try apply StringAVLSet.mem_2 in Heqin_b.
{
  apply StringAVLSet.union_1 in Heqin_ab.
  case Heqin_ab; intro H; apply StringAVLSet.mem_1 in H; rewrite H in *; easy.
}
{ now rewrite (StringAVLSet.mem_1 (StringAVLSet.union_2 b Heqin_a)) in Heqin_ab. }
{ now rewrite (StringAVLSet.mem_1 (StringAVLSet.union_2 b Heqin_a)) in Heqin_ab. }
now rewrite (StringAVLSet.mem_1 (StringAVLSet.union_3 a Heqin_b)) in Heqin_ab.
Qed.

Lemma string_avl_set_inter_ok a b x:
  StringAVLSet.mem x (StringAVLSet.inter a b) = StringAVLSet.mem x a && StringAVLSet.mem x b.
Proof.
remember (StringAVLSet.mem x (StringAVLSet.inter a b)) as in_ab.
remember (StringAVLSet.mem x a) as in_a.
remember (StringAVLSet.mem x b) as in_b.
symmetry in Heqin_ab. symmetry in Heqin_a. symmetry in Heqin_b.
destruct in_ab; destruct in_a; destruct in_b; cbn; trivial; exfalso;
  try apply StringAVLSet.mem_2 in Heqin_ab;
  try apply StringAVLSet.mem_2 in Heqin_a;
  try apply StringAVLSet.mem_2 in Heqin_b.
{
  apply StringAVLSet.inter_2 in Heqin_ab.
  apply StringAVLSet.mem_1 in Heqin_ab.
  rewrite Heqin_ab in Heqin_b. discriminate.
}
{
  apply StringAVLSet.inter_1 in Heqin_ab.
  apply StringAVLSet.mem_1 in Heqin_ab.
  rewrite Heqin_ab in Heqin_a. discriminate.
}
{
  apply StringAVLSet.inter_1 in Heqin_ab.
  apply StringAVLSet.mem_1 in Heqin_ab.
  rewrite Heqin_ab in Heqin_a. discriminate.
}
now rewrite (StringAVLSet.mem_1 (StringAVLSet.inter_3 Heqin_a Heqin_b)) in Heqin_ab.
Qed.

Lemma string_avl_set_diff_ok a b x:
  StringAVLSet.mem x (StringAVLSet.diff a b) = StringAVLSet.mem x a && negb (StringAVLSet.mem x b).
Proof.
remember (StringAVLSet.mem x (StringAVLSet.diff a b)) as in_ab.
remember (StringAVLSet.mem x a) as in_a.
remember (StringAVLSet.mem x b) as in_b.
symmetry in Heqin_ab. symmetry in Heqin_a. symmetry in Heqin_b.
destruct in_ab; destruct in_a; destruct in_b; cbn; trivial;
  try apply StringAVLSet.mem_2 in Heqin_ab;
  try apply StringAVLSet.mem_2 in Heqin_a;
  try apply StringAVLSet.mem_2 in Heqin_b.
{ now apply StringAVLSet.diff_2 in Heqin_ab. }
{
  apply StringAVLSet.diff_1 in Heqin_ab.
  apply StringAVLSet.mem_1 in Heqin_ab.
  rewrite Heqin_ab in Heqin_a. discriminate.
}
{
  apply StringAVLSet.diff_1 in Heqin_ab.
  apply StringAVLSet.mem_1 in Heqin_ab.
  rewrite Heqin_ab in Heqin_a. discriminate.
}
apply StringAVLSet.diff_3 with (s' := b) in Heqin_a.
{
  apply StringAVLSet.mem_1 in Heqin_a.
  rewrite Heqin_ab in Heqin_a. discriminate.
}
intro H. apply StringAVLSet.mem_1 in H.
rewrite H in Heqin_b. discriminate.
Qed.

Lemma string_avl_set_forall_ok s (p: String.string -> bool):
  StringAVLSet.for_all p s = true
   <->
  forall x,
    StringAVLSet.mem x s = true -> p x = true.
Proof.
split; intro H.
{
  apply StringAVLSet.for_all_2 in H.
  {
    intros x XIn.
    unfold StringAVLSet.For_all in H.
    apply StringAVLSet.mem_2 in XIn.
    exact (H x XIn).
  }
  intros x y E. now subst.
}
apply StringAVLSet.for_all_1.
{ intros x y E. now subst. }
intros x XIn.
apply H.
now apply StringAVLSet.mem_1.
Qed.

Lemma string_avl_set_subset_ok a b:
 StringAVLSet.subset a b = true
  <->
 forall x,
   negb (StringAVLSet.mem x a) || StringAVLSet.mem x b = true.
Proof.
split; intro H.
{
  apply StringAVLSet.subset_2 in H.
  unfold StringAVLSet.Subset in H.
  intro x.
  remember (StringAVLSet.mem x a) as in_a.
  remember (StringAVLSet.mem x b) as in_b.
  symmetry in Heqin_a. symmetry in Heqin_b.
  destruct in_a; destruct in_b; cbn; trivial;
    try apply StringAVLSet.mem_2 in Heqin_a;
    try apply StringAVLSet.mem_2 in Heqin_b.
  now rewrite (StringAVLSet.mem_1 (H _ Heqin_a)) in Heqin_b.
}
apply StringAVLSet.subset_1.
intros x InA.
apply StringAVLSet.mem_1 in InA.
apply StringAVLSet.mem_2.
assert (Q := H x).
rewrite InA in Q.
remember (StringAVLSet.mem x b) as in_b.
symmetry in Heqin_b. destruct in_b; trivial.
Qed.

Lemma string_avl_set_eq_ok a b:
  StringAVLSet.equal a b = true
   <->
  forall x,
    StringAVLSet.mem x a = StringAVLSet.mem x b.
Proof.
split; intro H.
{
  intro x.
  apply StringAVLSet.equal_2 in H.
  unfold StringAVLSet.Equal in H.
  remember (StringAVLSet.mem x a) as in_a.
  remember (StringAVLSet.mem x b) as in_b.
  symmetry. symmetry in Heqin_a. symmetry in Heqin_b.
  destruct in_a; destruct in_b; cbn; trivial;
    try apply StringAVLSet.mem_2 in Heqin_a;
    try apply StringAVLSet.mem_2 in Heqin_b;
    try discriminate.
  {
    rewrite (H x) in Heqin_a;
    rewrite (StringAVLSet.mem_1 Heqin_a) in Heqin_b.
    discriminate.
  }
  rewrite<- (H x) in Heqin_b.
  rewrite (StringAVLSet.mem_1 Heqin_b) in Heqin_a.
  discriminate.
}
apply StringAVLSet.equal_1.
unfold StringAVLSet.Equal.
intro x.
remember (StringAVLSet.mem x a) as in_a.
remember (StringAVLSet.mem x b) as in_b.
symmetry. symmetry in Heqin_a. symmetry in Heqin_b.
destruct in_a; destruct in_b; cbn; trivial;
  try (rewrite (H x) in Heqin_a; rewrite Heqin_a in Heqin_b; discriminate);
  try apply StringAVLSet.mem_2 in Heqin_a;
  try apply StringAVLSet.mem_2 in Heqin_b;
  try tauto.
split; intro Z; apply StringAVLSet.mem_1 in Z; rewrite Z in *; discriminate.
Qed.

Instance string_avl_set_impl: class String.string_dec string_avl_set
:= {|
      to_list := StringAVLSet.elements;
      to_list_nodup := string_avl_set_to_list_nodup;
      from_list l := fold_right StringAVLSet.add StringAVLSet.empty l;
      has s x := StringAVLSet.mem x s;
      has_to_list := string_avl_set_in_to_list;
      has_from_list := string_avl_set_in_from_list;
      empty := StringAVLSet.empty;
      empty_to_list := eq_refl;
      singleton := StringAVLSet.singleton;
      singleton_to_list s := eq_refl;
      size_nat := StringAVLSet.cardinal;
      size_nat_to_list := StringAVLSet.cardinal_1;
      is_empty := StringAVLSet.is_empty;
      is_empty_to_list := string_avl_set_empty_to_list;
      size s := N.of_nat (StringAVLSet.cardinal s);
      size_ok s := eq_refl;
      add s x := StringAVLSet.add x s;
      add_ok s x := string_avl_set_add_ok x s;
      remove s x := StringAVLSet.remove x s;
      remove_ok s x := string_avl_set_remove_ok x s;
      union := StringAVLSet.union;
      union_ok := string_avl_set_union_ok;
      inter := StringAVLSet.inter;
      inter_ok := string_avl_set_inter_ok;
      diff := StringAVLSet.diff;
      diff_ok := string_avl_set_diff_ok;
      for_all s p := StringAVLSet.for_all p s;
      for_all_ok := string_avl_set_forall_ok;
      is_subset := StringAVLSet.subset;
      is_subset_ok := string_avl_set_subset_ok;
      equal := StringAVLSet.equal;
      equal_ok := string_avl_set_eq_ok;
   |}.

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

Section SetFacts.

Context {M: Type} {E: forall x y: M, {x = y} + {x <> y}} {S: Type} {C: class E S}.

Lemma empty_ok (x: M):
  has empty x = false.
Proof.
rewrite has_to_list.
rewrite empty_to_list; auto.
Qed.

Lemma singleton_ok (x y: M):
  has (singleton x) y = true <-> x = y.
Proof.
rewrite has_to_list.
rewrite singleton_to_list.
cbn.
destruct E as [EQ|NE]. { symmetry in EQ. tauto. }
split; intro H. { congruence. }
symmetry in H. contradiction.
Qed.

Lemma is_empty_true (a: S) (H: is_empty a = true) (x: M):
  has a x = false.
Proof.
rewrite has_to_list. rewrite is_empty_to_list in H.
rewrite H. trivial.
Qed.

Lemma is_empty_false (a: S) (H: is_empty a = false):
  exists x: M,
    has a x = true.
Proof.
remember (to_list a) as l.
destruct l.
{
  symmetry in Heql. rewrite<- is_empty_to_list in Heql.
  rewrite Heql in H. congruence.
}
exists m.
rewrite has_to_list.
rewrite<- Heql.
cbn. now destruct E.
Qed.

Lemma add_has (x: M) (s: S):
  has (add s x) x = true.
Proof.
rewrite add_ok. now destruct E.
Qed.

Lemma is_subset_refl (a: S):
  is_subset a a = true.
Proof.
rewrite is_subset_ok. intro x.
bool. destruct has; tauto.
Qed.

Lemma is_subset_equal (a b: S) (Eq: equal a b = true):
  is_subset a b = true.
Proof.
rewrite is_subset_ok. rewrite equal_ok in Eq. intro x.
rewrite (Eq x).
destruct has; tauto.
Qed.

Lemma is_subset_trans {a b c: S}
                      (AB: is_subset a b = true)
                      (BC: is_subset b c = true):
  is_subset a c = true.
Proof.
rewrite is_subset_ok in *. intro x.
assert (ABx := AB x).
assert (BCx := BC x).
bool.
destruct has; destruct has; destruct has; tauto.
Qed.

Lemma is_subset_antisym {a b: S}
                        (AB: is_subset a b = true)
                        (BC: is_subset b a = true):
  equal a b = true.
Proof.
rewrite is_subset_ok in AB.
rewrite is_subset_ok in BC.
rewrite equal_ok. intro x.
assert (ABx := AB x).
assert (BCx := BC x).
bool.
destruct has; destruct has; trivial; case ABx; case BCx; try tauto;
  intros; try tauto; symmetry; tauto.
Qed.

Lemma add_subset (x: M) (s: S):
  is_subset s (add s x) = true.
Proof.
rewrite is_subset_ok. intro y.
rewrite add_ok. bool. destruct (E x y); try tauto.
destruct has; tauto.
Qed.

Lemma union_subset_l (a b: S):
  is_subset a (union a b) = true.
Proof.
rewrite is_subset_ok. intro x.
rewrite union_ok.
destruct has; now destruct has.
Qed.

Lemma union_subset_r (a b: S):
  is_subset b (union a b) = true.
Proof.
rewrite is_subset_ok. intro x.
rewrite union_ok.
destruct has; now destruct has.
Qed.

Lemma inter_subset_l (a b: S):
  is_subset (inter a b) a = true.
Proof.
rewrite is_subset_ok. intro x.
rewrite inter_ok.
destruct has; now destruct has.
Qed.

Lemma inter_subset_r (a b: S):
  is_subset (inter a b) b = true.
Proof.
rewrite is_subset_ok. intro x.
rewrite inter_ok.
destruct has; now destruct has.
Qed.

Lemma union_monotonic_l (a b c: S)
                        (H: is_subset a b = true):
  is_subset (union a c) (union b c) = true.
Proof.
rewrite is_subset_ok in *. intro x.
repeat rewrite union_ok.
assert (Hx := H x). clear H.
destruct (has a x); destruct (has b x); destruct (has c x); tauto.
Qed.

Lemma union_monotonic_r (a b c: S)
                        (H: is_subset b c = true):
  is_subset (union a b) (union a c) = true.
Proof.
rewrite is_subset_ok in *. intro x.
repeat rewrite union_ok.
assert (Hx := H x). clear H.
destruct (has a x); destruct (has b x); destruct (has c x); tauto.
Qed.

Lemma inter_monotonic_l (a b c: S)
                        (H: is_subset a b = true):
  is_subset (inter a c) (inter b c) = true.
Proof.
rewrite is_subset_ok in *. intro x.
repeat rewrite inter_ok.
assert (Hx := H x). clear H.
destruct (has a x); destruct (has b x); destruct (has c x); tauto.
Qed.

Lemma inter_monotonic_r (a b c: S)
                        (H: is_subset b c = true):
  is_subset (inter a b) (inter a c) = true.
Proof.
rewrite is_subset_ok in *. intro x.
repeat rewrite inter_ok.
assert (Hx := H x). clear H.
destruct (has a x); destruct (has b x); destruct (has c x); tauto.
Qed.

End SetFacts.


(*|
##############################################################
Proving uniqueness of an instance of an indexed inductive type
##############################################################

:Link: https://proofassistants.stackexchange.com/q/1246
|*)

(*|
Question
********

Consider the simple indexed inductive type
|*)

Inductive Single : nat -> Set :=
| single_O : Single O
| single_S {n} : Single n -> Single (S n).

(*|
Intuitively, I thought that ``Single n`` has a unique value for each
``n : nat``. I started by trying to prove that ``forall s : Single O,
s = single_O``. However, the usual tactics ``inversion``,
``destruct``, and ``induction`` did not work:
|*)

Lemma single_O_unique (s : Single O) : s = single_O.
  inversion s. (* No effect *)
  Fail destruct s.
  Fail induction s.

(*| The error messages were: |*)

  Fail destruct s. (* .unfold .messages *)

(*| So I resorted to a manual ``match`` expression: |*)

  refine match s with
         | single_O => _
         | single_S _ => _
         end.

(*| Resulting in the following proof context: |*)

  Show. (* .unfold .messages *)

(*| which was puzzling, but easy to prove: |*)

  - reflexivity.
  - exact idProp.
Qed.

(*|
Questions:

- Why was ``inversion`` unable to recognize that ``s`` could only be
  ``single_O`` and substitute accordingly?
- Why did the ``refine`` tactic produce the subgoal ``IDProp``?
- Is there a way to get ``inversion`` or ``destruct`` to work in this
  case? Or, what would a better way to prove ``s = single_O``?

Full example:
|*)

Reset Initial. (* .none *)
Inductive Single : nat -> Set :=
| single_O : Single O
| single_S {n} : Single n -> Single (S n).

Lemma single_O_unique (s : Single O) : s = single_O.
  inversion s.  (* No effect *)
  Fail destruct s.
  Fail induction s.
  refine match s with
         | single_O => _
         | single_S _ => _
         end.
  - reflexivity.
  - exact idProp.
Qed.

(*|
Answer (gallais)
****************

    Or, what would a better way to prove ``s = single_O``?

I would define a function that, given a nat ``n``, computes the
canonical proof ``Single n``.
|*)

Reset single_O_unique. (* .none *)
Fixpoint Canonical (n : nat) : Single n :=
  match n with
  | O => single_O
  | S n => single_S (Canonical n)
  end.

(*|
You can then easily prove that any ``Single n`` proof is equal to the
canonical one by induction. Here the abstraction won't fail because
the equality is already generic over ``n``.
|*)

Lemma single_canonical (n : nat) (s : Single n) : s = Canonical n.
Proof.
  induction s.
  - reflexivity.
  - simpl. f_equal. assumption.
Qed.

(*| Your original lemma is then a direct corollary. |*)

Lemma single_O_unique (s : Single O) : s = single_O.
  apply single_canonical with (n := O).
Qed.

(*|
Answer (Meven Lennon-Bertrand)
******************************

Regarding ``IDProp``, this is the pattern-matching compilation of Coq
at work. Basically, because you scrutinee has a type that can only
correspond to the ``single_O`` branch, Coq was smart enough to craft a
return predicate that gave you an interesting goal only in that
branch, the other being replaced by the trivially inhabited ``IDProp``
(as you noticed in your proof). So ``match`` was smart enough "to
recognize that ``s`` could only be ``single_O``". If you wish to see
what exactly happened, you can use the ``Show Proof.`` command.

I'm a bit suprised that ``destruct``, ``inversion`` and friends, which
are supposed to be built on top of pattern-matching, were not able to
succeed where the simpler ``refine (match …)`` was. In such cases with
complex dependencies, ``dependent inversion`` works better than
``inversion``, but it still fails here, sadly.

If you wish to have ``inversion`` work here, you'd have to replace
``single_O`` by something generic enough. Using gallais' solution, you
can do
|*)

Reset Canonical. (* .none *)
Fixpoint Canonical (n : nat) : Single n :=
  match n with
  | O => single_O
  | S n => single_S (Canonical n)
  end.

Lemma single_O_can (s : Single 0) : s = single_O.
Proof.
  change single_O with (Canonical 0).
  dependent inversion s.
  reflexivity.
Qed.

(*|
Now ``dependent inversion`` succeeds because ``Canonical 0`` can
successfully be abstracted over ``0``, while ``single_O`` could not.
|*)


Inductive Ty: Set :=
  ty_o: Ty | ty_arr: Ty -> Ty -> Ty.

Inductive Con: Set :=
  con_empty: Con | con_cons: Con -> Ty -> Con.

Inductive Var: Con -> Ty -> Set :=
  | var_zero: forall g s, Var (con_cons g s) s
  | var_suc: forall g t s, Var g s -> Var (con_cons g t) s.

Inductive Tm: Con -> Ty -> Set :=
  | tm_var: forall g s, Var g s -> Tm g s
  | tm_app: forall g s t, Tm g (ty_arr s t) -> Tm g s -> Tm g t
  | tm_lam: forall g s t, Tm (con_cons g s) t -> Tm g (ty_arr s t).


Require Import Omega.

Local Open Scope nat_scope.

Inductive period : Type :=
| Period (a b : nat).

Definition pstart (p : period) : nat :=
  match p with | Period a b => a end.

Definition pend (p : period) : nat :=
  match p with | Period a b => b end.

Inductive periodR : period -> Prop :=
| PeriodR : forall p,
    (* By definition, a period's end tstamp is strictly greater than its start. *)
    pstart p < pend p ->
    periodR p.

Inductive overlapsTeradataR : period -> period -> Prop :=
| TeradataSGt : forall p1 p2,
    periodR p1 ->
    periodR p2 ->
    (pstart p1) > (pstart p2) ->
    ~ (pstart p1 >= pend p2 /\ pend p1 >= pend p2) ->
    (overlapsTeradataR p1 p2)
| TeradataSLt : forall p1 p2,
    periodR p1 ->
    periodR p2 ->
    (pstart p2) > (pstart p1) ->
    ~ (pstart p2 >= pend p1 /\ pend p2 >= pend p1) ->
    (overlapsTeradataR p1 p2)
| TeradataSEq : forall p1 p2,
    periodR p1 ->
    periodR p2 ->
    pstart p1 = pstart p2 ->
    (pend p1 = pend p2 \/ pend p1 <> pend p2) ->
    (overlapsTeradataR p1 p2).

Inductive overlapsBigQueryR : period -> period -> Prop :=
| BigQuery : forall p1 p2,
    periodR p1 ->
    periodR p2 ->
    max (pstart p1) (pstart p2) < min (pend p1) (pend p2) ->
    (overlapsBigQueryR p1 p2).

Theorem overlaps_Teradata_BigQuery_equiv : forall p1 p2 : period,
    overlapsTeradataR p1 p2 <-> overlapsBigQueryR p1 p2.
Proof.
  split.
  - intros H. inversion H; subst;
    inversion H0; inversion H1; subst; apply BigQuery; try assumption;
      try (apply Decidable.not_and in H3; try apply dec_ge);
      destruct H3 as [|].
      * rewrite max_l.
        + apply not_le in H3. apply Nat.min_glb_lt; assumption.
        + apply not_ge in H3. rewrite Nat.lt_eq_cases. left. assumption.
      * rewrite min_l; apply not_ge in H3.
        + rewrite max_l. assumption.
          rewrite Nat.lt_eq_cases. left. assumption.
        + rewrite Nat.lt_eq_cases. left. assumption.
      * rewrite max_r.
        + apply not_ge in H3. apply Nat.min_glb_lt; assumption.
        + rewrite Nat.lt_eq_cases. left. assumption.
      * rewrite max_r.
        + rewrite min_r. assumption.
          rewrite Nat.lt_eq_cases. apply not_ge in H3. left. assumption.
        + rewrite Nat.lt_eq_cases. left. assumption.
      * rewrite max_r.
        + rewrite min_r. assumption.
          rewrite Nat.lt_eq_cases. right. symmetry. assumption.
        + rewrite Nat.lt_eq_cases. right. assumption.
      * rewrite max_r.
        + rewrite H2 in H4. apply Nat.min_glb_lt; assumption.
        + rewrite Nat.lt_eq_cases. right. assumption.
  - intros H. inversion H. subst.
    apply Nat.max_lub_lt_iff in H2.
    destruct H2 as [H3 H4].
    apply Nat.min_glb_lt_iff in H3.
    apply Nat.min_glb_lt_iff in H4.
    destruct H3. destruct H4.
    assert (HMQ:=Nat.max_spec (pstart p1) (pstart p2)).
    destruct HMQ as [|]; destruct H6 as [].
    * apply TeradataSLt.
      apply PeriodR. assumption. assumption. assumption.
      unfold not. intros. destruct H8 as []. intuition.
    * rewrite Nat.lt_eq_cases in H6. destruct H6 as [|].
      + apply TeradataSGt.
        apply PeriodR. assumption. assumption. assumption.
        unfold not. intros. destruct H8 as []. intuition.
      + apply TeradataSEq.
        apply PeriodR. assumption. assumption. auto.
        decide equality.
Qed.


Theorem ExF002 {X : Type} (P Q : X -> Prop) (a : X): (forall x, P x -> Q x) -> P a -> Q a.
Proof.
  intros.
  specialize (H a).
  apply H.
  exact H0.
Qed.


Require Coq.Setoids.Setoid.
(*
	The following axiom systems are used to formalize
	Euclid's proofs of Euclid's Elements.OriginalProofs.statements.
*)

(*
	First, we define an axiom system for neutral geometry,
	i.e. geometry without continuity axioms nor parallel postulate.
*)

Class euclidean_neutral :=
{
	Point : Type;
	Circle : Type;
	Cong : Point -> Point -> Point -> Point -> Prop;
	BetS : Point -> Point -> Point -> Prop;
	(* TODO: rename to Circle *)
	CI : Circle -> Point -> Point -> Point -> Prop;
	eq := @eq Point;
	neq A B := ~ eq A B;
	nCol A B C := neq A B /\ neq A C /\ neq B C /\ ~ BetS A B C /\ ~ BetS A C B /\ ~ BetS B A C;
	Col A B C := (eq A B \/ eq A C \/ eq B C \/ BetS B A C \/ BetS A B C \/ BetS A C B);
	(* C and D are on opposite sides of AB *)
	(* TODO: rename to OppositeSides *)
	OS P A B Q := exists X, BetS P X Q /\ Col A B X /\ nCol A B P;
	Triangle A B C := nCol A B C;

	OnCirc B J := exists X Y U, CI J U X Y /\ Cong U B X Y;
	InCirc P J := exists X Y U V W, CI J U V W /\ (eq P U \/ (BetS U Y X /\ Cong U X V W /\ Cong U P U Y));
	OutCirc P J := exists X U V W, CI J U V W /\ BetS U X P /\ Cong U X V W;

	cn_congruencetransitive :
		forall A B C D E F, Cong A B C D -> Cong A B E F -> Cong C D E F;
	cn_congruencereflexive :
		forall A B, Cong A B A B;
	(* Originally known as cn_equalityreverse *)
	cn_congruencereverse :
		forall A B, Cong A B B A;
	cn_sumofparts :
		forall A B C a b c,
			Cong A B a b -> Cong B C b c -> BetS A B C -> BetS a b c -> Cong A C a c;

	axiom_circle_center_radius :
		forall A B C J P, CI J A B C -> OnCirc P J -> Cong A P B C;
	axiom_betweennessidentity :
		forall A B, ~ BetS A B A;
	axiom_betweennesssymmetry :
		forall A B C, BetS A B C -> BetS C B A;
	(* Originally known as axiom_innertransitivity *)
	axiom_orderofpoints_ABD_BCD_ABC :
		forall A B C D,
			BetS A B D -> BetS B C D -> BetS A B C;
	axiom_connectivity :
		forall A B C D,
			BetS A B D -> BetS A C D -> ~ BetS A B C -> ~ BetS A C B ->
			eq B C;

	axiom_nocollapse :
		forall A B C D, neq A B -> Cong A B C D -> neq C D;
	(* 6.4 Five-line axiom *)
	(* Called Five Segment in Tarski *)
	(*
		The order and list of antecedents is changed to make the axiom easier to remember.

		0.	Not stated: ∃ △ABD , △abd , △DBC , △dbc , possibly degenerate.

		1.	△ABD ≅ △abd by SSS congruence.

		2.	(B(A,B,C) /\ B(a,b,c)) implies that
			∠ABD is supplement to ∠DBC and ∠abd is supplement to ∠dbc .
		3.	#1 implies that ∠ABD ≅ ∠abd .
		4.	#2 and #3 imply that ∠DBC ≅ ∠dbc .

		5.	(DB ≅ db /\ ∠DBC ≅ ∠dbc (from #4) /\ BC ≅ bc) implies that
			△DBC ≅ △dbc by SAS congruence.
	*)
	(*
		Adding lemma_5_line_degenerate would make it obvious when degenerate triangles are used.
		This is not done, since axiom_5_line is commonly used to help prove betweenness or equality,
		which are needed to show that the triangles used are in fact degenerate.
	*)
	axiom_5_line :
		forall A B C D a b c d,
			Cong A B a b ->
			Cong B D b d ->
			Cong D A d a ->

			BetS A B C ->
			BetS a b c ->

			Cong D B d b ->
			Cong B C b c ->

			Cong C D c d;

	postulate_Pasch_inner :
		forall A B C P Q,
			BetS A P C -> BetS B Q C -> nCol A C B ->
			exists X, BetS A X Q /\ BetS B X P;
	postulate_Pasch_outer :
		forall A B C P Q,
			BetS A P C -> BetS B C Q -> nCol B Q A ->
			exists X, BetS A X Q /\ BetS B P X;

	postulate_Euclid2 : forall A B, neq A B -> exists X, BetS A B X;
	postulate_Euclid3 : forall A B, neq A B -> exists X, CI X A A B;
}.

(*
	Second, we enrich the axiom system with line-circle
	and circle-circle continuity axioms.
	Those two axioms state that we allow ruler and compass constructions.
*)

Class euclidean_neutral_ruler_compass `(Ax : euclidean_neutral) :=
{
	postulate_line_circle :
		forall A B C K P Q,
			CI K C P Q -> InCirc B K -> neq A B ->
			exists X Y, Col A B X /\ BetS A B Y /\ OnCirc X K /\ OnCirc Y K /\ BetS X B Y;
	postulate_circle_circle :
		forall C D F G J K P Q R S,
			CI J C R S -> InCirc P J ->
			OutCirc Q J -> CI K D F G ->
			OnCirc P K -> OnCirc Q K ->
			exists X, OnCirc X J /\ OnCirc X K
}.


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

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


Require Import Coq.Classes.Equivalence.
Require Import Coq.Classes.Morphisms.
Require Import Coq.Classes.RelationClasses.
Require Import Coq.QArith.QArith.
Require Import Coq.QArith.Qminmax.
Require Import Coq.Relations.Relations.
Require Import Coq.Setoids.Setoid.
Require Import Coq.Unicode.Utf8.
Require Import Iteration.Lattice.

(* Rationals with ±+∞ *)

Reserved Notation "+∞" (at level 0).
Reserved Notation "-∞" (at level 0).

Declare Scope QInf_scope.
Delimit Scope QInf_scope with QInf.

Module QInf.

  Local Open Scope Q_scope.
  Local Open Scope QInf_scope.

  Inductive t :=
    NegInf : t
  | PosInf : t
  | Fin : Q → t.

  Coercion Fin : Q >-> t.

  Notation "+∞" := PosInf : QInf_scope.
  Notation "-∞" := NegInf : QInf_scope.

  Definition eqb n m :=
    match n, m with
    | +∞, +∞ => true
    | -∞, -∞ => true
    | Fin n, Fin m => Qeq_bool n m
    | _, _ => false
    end.

  Definition eq n m := eqb n m = true.

  Infix "==" := eq : QInf_scope.

  Hint Unfold eq eqb : core.

  Lemma eq_refl : Reflexive eq.
  Proof.
    intros x.
    destruct x; try reflexivity.
    apply Qeq_bool_refl.
  Qed.

  Lemma eq_sym : Symmetric eq.
  Proof.
    intros x y H.
    destruct x; destruct y; inversion H; try reflexivity.
    apply Qeq_bool_sym.
    assumption.
  Qed.

  Lemma eq_trans : Transitive eq.
  Proof.
    intros x y z P Q.
    destruct x; destruct y; destruct z; inversion P; inversion Q; try reflexivity.
    apply (Qeq_bool_trans _ _ _ P Q).
  Qed.

  Lemma eq_Qeq : ∀ x y, (x == y)%Q → (x == y)%QInf.
  Proof.
    intros x y.
    apply Qeq_bool_iff.
  Qed.

  Global Instance Equivalence_eq : Equivalence eq := {|
    Equivalence_Reflexive := eq_refl;
    Equivalence_Symmetric := eq_sym;
    Equivalence_Transitive := eq_trans;
  |}.

  Add Relation t eq
    reflexivity proved by eq_refl
    symmetry proved by eq_sym
    transitivity proved by eq_trans
    as eq_qinf_rel.

  Definition leb n m :=
    match n, m with
    | +∞, +∞ => true
    | +∞, _ => false
    | _, +∞ => true
    | -∞, _ => true
    | _, -∞ => false
    | Fin n, Fin m => Qle_bool n m
    end.

  Definition le n m := leb n m = true.

  Infix "<=" := le : QInf_scope.
  Infix "≤" := le : QInf_scope.

  Hint Unfold le leb : core.

  Lemma le_refl : Reflexive le.
  Proof.
    intros x.
    destruct x; try reflexivity.
    unfold le, leb.
    rewrite Qle_bool_iff.
    apply Qle_refl.
  Qed.

  Lemma le_trans : Transitive le.
  Proof.
    intros x y z P Q.
    destruct x; destruct y; destruct z; inversion P; inversion Q; try reflexivity.
    unfold le, leb in *.
    rewrite Qle_bool_iff in *.
    apply (Qle_trans _ _ _ P Q).
  Qed.

  Global Instance PreOrder_le : PreOrder le := {|
    PreOrder_Reflexive := le_refl;
    PreOrder_Transitive := le_trans;
  |}.

  Global Instance PartialOrder_eq_le : PartialOrder eq le.
  Proof.
    intros x y.
    split.
    - intros H.
      split;
        destruct x; destruct y; inversion H; try reflexivity;
        apply Qle_bool_iff;
        apply Qeq_bool_eq in H1;
        rewrite H1;
        apply Qle_refl.
    - intros H.
      destruct H as [P Q].
      destruct x; destruct y; inversion P; inversion Q; try reflexivity.
      apply Qeq_eq_bool.
      apply Qle_bool_iff in H0.
      apply Qle_bool_iff in H1.
      apply (Qle_antisym _ _ H0 H1).
  Qed.

  Add Morphism le with
    signature eq ==> eq ==> iff as le_mor.
  Proof.
    intros x y P z w Q.
    split.
    - intros H.
      destruct x; destruct y; destruct z; destruct w;
      inversion P; inversion Q; inversion H; try reflexivity.
      apply Qle_bool_iff.
      apply Qeq_bool_eq in H1.
      apply Qeq_bool_eq in H2.
      apply Qle_bool_iff in H3.
      rewrite H2 in H3.
      rewrite H1 in H3.
      assumption.
    - intros H.
      destruct x; destruct y; destruct z; destruct w;
      inversion P; inversion Q; inversion H; unfold le, leb; try reflexivity.
      apply Qle_bool_iff.
      apply Qeq_bool_eq in H1.
      apply Qeq_bool_eq in H2.
      apply Qle_bool_iff in H3.
      rewrite <- H2 in H3.
      rewrite <- H1 in H3.
      assumption.
  Qed.

  Definition add n m :=
    match n with
    | -∞ => -∞
    | +∞ => +∞
    | Fin n => n + m
    end.

  Infix "+" := add : QInf_scope.

  Add Morphism add with
    signature eq ==> Qeq ==> eq as add_mor.
  Proof.
    intros x y P z w Q.
    destruct x; destruct y; destruct z; destruct w;
    inversion P; inversion Q; try reflexivity.
    clear H1.
    remember (Qnum # Qden) as x.
    remember (Qnum0 # Qden0) as y.
    unfold add, eq, eqb in *.
    apply Qeq_bool_iff.
    apply Qeq_bool_iff in P.
    rewrite P.
    rewrite Q.
    reflexivity.
  Qed.

  Definition sub n m :=
    match n with
    | -∞ => -∞
    | +∞ => +∞
    | Fin n => n - m
    end.

  Infix "-" := sub : QInf_scope.

  Add Morphism sub with
    signature eq ==> Qeq ==> eq as sub_mor.
  Proof.
    intros x y P z w Q.
    destruct x; destruct y; destruct z; destruct w;
    inversion P; inversion Q; try reflexivity.
    clear H1.
    remember (Qnum # Qden) as x.
    remember (Qnum0 # Qden0) as y.
    unfold sub, eq, eqb in *.
    apply Qeq_bool_iff.
    apply Qeq_bool_iff in P.
    rewrite P.
    rewrite Q.
    reflexivity.
  Qed.

  Definition min n m :=
    match n, m with
    | -∞, _ => -∞
    | _, -∞ => -∞
    | +∞, m => m
    | n, +∞ => n
    | Fin n, Fin m => Qmin n m
    end.

  Lemma min_comm : ∀ n m, (min n m == min m n)%QInf.
  Proof.
    intros n m.
    destruct n; destruct m; try reflexivity.
    apply Qeq_bool_iff.
    apply Q.min_comm.
  Qed.

  Lemma min_id : ∀ n, (min n n == n)%QInf.
  Proof.
    intros n.
    destruct n; try reflexivity.
    apply Qeq_bool_iff.
    apply Q.min_id.
  Qed.

  Lemma min_posinf : ∀ n, (min n +∞ == n)%QInf.
  Proof.
    intros n. destruct n; reflexivity.
  Qed.

  Lemma min_assoc : ∀ m n p, (min m (min n p) == min (min m n) p)%QInf.
  Proof.
    intros m n p.
    destruct m; destruct n; destruct p; try reflexivity.
    apply Qeq_bool_iff.
    apply Q.min_assoc.
  Qed.

  Add Morphism min with
    signature eq ==> eq ==> eq as min_mor.
  Proof.
    intros x y P z w Q.
    destruct x; destruct y; destruct z; destruct w;
    inversion P; inversion Q; try reflexivity;
    unfold eq, eqb in *; simpl;
    apply Qeq_bool_iff.
    apply Qeq_bool_iff in Q.
    assumption.
    apply Qeq_bool_iff in P.
    assumption.
    apply Qeq_bool_iff in Q.
    apply Qeq_bool_iff in P.
    rewrite P.
    rewrite Q.
    reflexivity.
  Qed.

  Definition max n m :=
    match n, m with
    | +∞, _ => +∞
    | _, +∞ => +∞
    | -∞, m => m
    | n, -∞ => n
    | Fin n, Fin m => Qmax n m
    end.

  Lemma max_comm : ∀ n m, (max n m == max m n)%QInf.
  Proof.
    intros n m.
    destruct n; destruct m; try reflexivity.
    apply Qeq_bool_iff.
    apply Q.max_comm.
  Qed.

  Lemma max_id : ∀ n, (max n n == n)%QInf.
  Proof.
    intros n.
    destruct n; try reflexivity.
    apply Qeq_bool_iff.
    apply Q.max_id.
  Qed.

  Lemma max_neginf : ∀ n, (max n -∞ == n)%QInf.
  Proof.
    intros n. destruct n; reflexivity.
  Qed.

  Lemma max_assoc : ∀ m n p, (max m (max n p) == max (max m n) p)%QInf.
  Proof.
    intros m n p.
    destruct m; destruct n; destruct p; try reflexivity.
    apply Qeq_bool_iff.
    apply Q.max_assoc.
  Qed.

  Add Morphism max with
    signature eq ==> eq ==> eq as max_mor.
  Proof.
    intros x y P z w Q.
    destruct x; destruct y; destruct z; destruct w;
    inversion P; inversion Q; try reflexivity;
    unfold eq, eqb in *; simpl;
    apply Qeq_bool_iff.
    apply Qeq_bool_iff in Q.
    assumption.
    apply Qeq_bool_iff in P.
    assumption.
    apply Qeq_bool_iff in Q.
    apply Qeq_bool_iff in P.
    rewrite P.
    rewrite Q.
    reflexivity.
  Qed.

  Lemma min_max_absorption : ∀ n m, (max n (min n m) == n)%QInf.
  Proof.
    intros n m.
    destruct n; destruct m; try reflexivity; apply Qeq_bool_iff.
    - apply Q.max_id.
    - apply Q.min_max_absorption.
  Qed.

  Lemma max_min_absorption : ∀ n m, (min n (max n m) == n)%QInf.
  Proof.
    intros n m.
    destruct n; destruct m; try reflexivity; apply Qeq_bool_iff.
    - apply Q.max_id.
    - apply Q.max_min_absorption.
  Qed.

  Global Instance Lattice_QInf : Lattice t := {|
    meet := min;
    join := max;
    top := +∞;
    bot := -∞;

    meet_commutative := min_comm;
    meet_idempotent := min_id;
    meet_associative := min_assoc;
    meet_id := min_posinf;

    join_commutative := max_comm;
    join_idempotent := max_id;
    join_associative := max_assoc;
    join_id := max_neginf;

    meet_join_absorptive := max_min_absorption;
    join_meet_absorptive := min_max_absorption;

    meet_respectful := min_mor;
    join_respectful := max_mor;
  |}.

End QInf.

Coercion QInf.Fin : Q >-> QInf.t.
Notation "+∞" := QInf.PosInf : QInf_scope.
Notation "-∞" := QInf.NegInf : QInf_scope.
Infix "==" := QInf.eq : QInf_scope.
Infix "<=" := QInf.le : QInf_scope.
Infix "≤" := QInf.le : QInf_scope.
Infix "+" := QInf.add : QInf_scope.
Infix "-" := QInf.sub : QInf_scope.


(** 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 (y : natural) (z : natural) (lf2 : natural) (lf1 : natural)
  : natural := plus Zero lf1.


(** * Tactics: More Basic Tactics *)

(** This chapter introduces several more proof strategies and
    tactics that allow us to prove more interesting properties of
    functional programs.  We will see:

    - how to use auxiliary lemmas in both "forward-style" 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 create a strong induction hypothesis (and when such
      strengthening is required); and
    - more details on how to reason by case analysis. *)

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 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 before.  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] that binds 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.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** 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].  What are the 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 like to pull 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 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 (and in our
    informal understanding of how datatype declarations work in other
    programming languages) are two more facts:

    - The constructor [S] is _injective_.  That is, if [S n = S m], it
      must be the case 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 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 different.  (Since neither
    [true] nor [false] take any arguments, their injectivity is not an
    issue.)  And so on. *)

(** Coq provides a tactic called [inversion] that allows us to
    exploit these principles in proofs. To see how to use it, let's
    show explicitly that the [S] constructor is injective: *)

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

(** By writing [inversion H] at this point, we ask Coq to
    generate all equations that it can infer from [H] as additional
    hypotheses, replacing variables in the goal as it goes. In the
    present example, this amounts to adding a new hypothesis [H1 : n =
    m] and replacing [n] by [m] in the goal. *)

  inversion H. reflexivity.  Qed.

(** Here's a more interesting example that shows how multiple
    equations can be derived at once. *)

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

(** It is possible to name the equations that [inversion]
    generates with an [as ...] clause: *)

Theorem inversion_ex2 : forall (n m : nat),
  [n] = [m] ->
  n = m.
Proof.
  intros n o H. inversion H as [Hno]. reflexivity.  Qed.

(** **** Exercise: 1 star (inversion_ex3)  *)
Example inversion_ex3 : forall (X : Type) (x y z : X) (l j : list X),
  x :: y :: l = z :: j ->
  y :: l = x :: j ->
  x = y.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** While 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
    constructors and functions, which we will find useful 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.

(** When used on a hypothesis involving an equality between
    _different_ constructors (e.g., [S n = O]), [inversion] solves the
    goal immediately. To see why this makes sense, consider the
    following proof: *)

Theorem beq_nat_0_l : forall n,
   beq_nat 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'].
  - (* n = 0 *)
    intros H. reflexivity.

(** However, the second one doesn't look so simple: assuming
    [beq_nat 0 (S n') = true], we must show [S n' = 0], but the latter
    clearly contradictory!  The way forward lies in the assumption.
    After simplifying the goal state, we see that [beq_nat 0 (S n') =
    true] has become [false = true]: *)

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

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

    intros H. inversion H. Qed.

(** This is an instance of a general logical principle known as
    the _principle of explosion_, which asserts that a contradiction
    entails anything, even false things.  For instance: *)

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

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

(** If you find the principle of explosion confusing, remember
    that these proofs are not actually showing that the conclusion of
    the statement holds.  Rather, they are arguing that the situation
    described by the premise can never arise, so the implication is
    vacuous.  We'll explore the principle of explosion of more detail
    in the next chapter. *)

(** **** Exercise: 1 star (inversion_ex6)  *)
Example inversion_ex6 : forall (X : Type)
                          (x y z : X) (l j : list X),
  x :: y :: l = [] ->
  y :: l = z :: j ->
  x = z.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** To summarize this discussion, 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] has the following effect:

    - If [c] and [d] are the same constructor, then, by the
      injectivity of this constructor, we know 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, and the current goal doesn't have to be
      considered. In this case, [inversion H] marks the current goal
      as completed and pops it off the goal stack. *)

(* ################################################################# *)
(** * 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, [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
    produces 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, idiomatic use of Coq tends to favor backward reasoning,
    but in some situations the forward style can be easier to think
    about.  *)

(** **** Exercise: 3 stars, recommended (plus_n_n_injective)  *)
(** Practice using "in" variants in this exercise.  (Hint: use
    [plus_n_Sm].) *)

Theorem plus_n_n_injective : forall n m,
     n + n = m + m ->
     n = m.
Proof.
  intros n. induction n as [| n'].
    (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * 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 bit delicate: if we begin 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'].
  - (* n = O *) simpl. intros eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.
  - (* n = S n' *) intros eq. destruct m as [| m'].
    + (* m = O *) inversion 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: 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 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 about
    whether [double n] is [10], so [Q] is useless.) *)

(** 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
    then 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'].
  - (* n = O *) simpl. intros m eq. destruct m as [| m'].
    + (* m = O *) reflexivity.
    + (* m = S m' *) inversion eq.

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

(** Notice that both the goal and the induction hypothesis are
    different this time: 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'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'].
    + (* m = O *) simpl.

(** The 0 case is trivial: *)

      inversion 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'. inversion eq. reflexivity. Qed.

(** What you should take away from all this 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 following exercise requires the same pattern. *)

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

(** **** 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] to
    obtain a more general IH doesn't always work by itself; 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'].
  - (* m = O *) simpl. intros eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* n = S n' *)  apply f_equal.
        (* Stuck again here, just like before. *)
Abort.

(** The problem here 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 twist 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,
    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'].
  - (* m = O *) simpl. intros n eq. destruct n as [| n'].
    + (* n = O *) reflexivity.
    + (* n = S n' *) inversion eq.
  - (* m = S m' *) intros n eq. destruct n as [| n'].
    + (* n = O *) inversion eq.
    + (* 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 [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 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. [] *)

(** Before we close this section and move on to some exercises, let's
    digress briefly and use [beq_nat_true] to prove a similar property
    about identifiers that we'll need in later chapters: *)

Theorem beq_id_true : forall x y,
  beq_id x y = true -> x = y.
Proof.
  intros [m] [n]. simpl. intros H.
  assert (H' : m = n). { apply beq_nat_true. apply H. }
  rewrite H'. reflexivity.
Qed.

(** **** Exercise: 3 stars, recommended (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.
  (* 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] from [Lists]. *)

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

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

(** It sometimes happens that we need to manually unfold a Definition
    so that we can manipulate its right-hand side.  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 get stuck: [simpl] doesn't simplify anything at this point,
    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 facts 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, a deeper discussion of unfolding and simplification
    is in order.

    You may already have observed that tactics like [simpl],
    [reflexivity], and [apply] will often unfold the definitions of
    functions automatically when it 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.

(** However, this automatic unfolding is rather 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, itself, cannot 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.
  - 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 to finish the proof 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.
  - 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.  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).
    - (* beq_nat n 3 = true *) reflexivity.
    - (* beq_nat n 3 = false *) destruct (beq_nat n 5).
      + (* beq_nat n 5 = true *) reflexivity.
      + (* 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 ...].  But either
    [n] is equal to [3] or it isn't, so we can 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: 3 stars, optional (combine_split)  *)
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.
(** [] *)

(** However, [destruct]ing compound expressions requires a bit of
    care, as such [destruct]s can sometimes 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.

(** Now suppose that we want to convince Coq of the (rather
    obvious) fact 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 performed 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 [beq_nat 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 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, giving it a
    name that 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. *)
    - (* e3 = true *) apply beq_nat_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, allow us to finish the
        proof. *)
      destruct (beq_nat n 5) eqn:Heqe5.
        + (* e5 = true *)
          apply beq_nat_true in Heqe5.
          rewrite -> Heqe5. reflexivity.
        + (* 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.
  (* FILL IN HERE *) Admitted.
(** [] *)

(* ################################################################# *)
(** * 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]

      - [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 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
  (* REPLACE THIS LINE WITH   := _your_definition_ . *) . Admitted.

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

(** [] *)

(** **** 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.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 4 stars, advanced, recommended (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].

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

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

(** $Date: 2016-07-14 17:02:35 -0400 (Thu, 14 Jul 2016) $ *)


Require Import Maps.
Require Import Imp.

Definition aequiv (a1 a2 : aexp) : Prop :=
  forall (st:state),
    aeval st a1 = aeval st a2.

Definition bequiv (b1 b2 : bexp) : Prop :=
  forall (st:state),
    beval st b1 = beval st b2.

Definition cequiv (c1 c2 : com) : Prop :=
  forall (st st' : state),
    (ceval c1 st st') <-> (ceval c2 st  st').

Theorem aequiv_example:
  aequiv (AMinus (AId "X") (AId "X")) (ANum 0).
unfold aequiv.
intro st.
simpl.
induction (st "X"%string).
simpl. reflexivity.
simpl. rewrite IHn. reflexivity.
Qed.

Theorem bequiv_example:
  bequiv (BEq (AMinus (AId "X") (AId "X")) (ANum 0)) BTrue.
unfold bequiv.
intro st.
simpl.
induction (st "X"%string).
simpl. reflexivity.
simpl. rewrite IHn. reflexivity.
Qed.

Theorem skip_left: forall c, cequiv (CSeq CSkip c) c.
intro c.
unfold cequiv.
intros src dst.
split.
intro h.
inversion h as [ | | com1 com2 srcx tmp dstx youpi yapla com1eq srceq dsteq
| | | | ].


(************************************************************************)
(*         *   The Coq Proof Assistant / The Coq Development Team       *)
(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)
(* <O___,, *       (see CREDITS file for the list of authors)           *)
(*   \VV/  **************************************************************)
(*    //   *    This file is distributed under the terms of the         *)
(*         *     GNU Lesser General Public License Version 2.1          *)
(*         *     (see LICENSE file for the text of the license)         *)
(************************************************************************)

Require Export BinNums.
Require Import BinPos.

Local Open Scope N_scope.

(**********************************************************************)
(** * Binary natural numbers, definitions of operations *)
(**********************************************************************)

Module N.

Definition t := N.

(** ** Nicer name [N.pos] for contructor [Npos] *)

Notation pos := Npos.

(** ** Constants *)

Definition zero := 0.
Definition one := 1.
Definition two := 2.

(** ** Operation [x -> 2*x+1] *)

Definition succ_double x :=
  match x with
  | 0 => 1
  | pos p => pos p~1
  end.

(** ** Operation [x -> 2*x] *)

Definition double n :=
  match n with
  | 0 => 0
  | pos p => pos p~0
  end.

(** ** Successor *)

Definition succ n :=
  match n with
  | 0 => 1
  | pos p => pos (Pos.succ p)
  end.

(** ** Predecessor *)

Definition pred n :=
  match n with
  | 0 => 0
  | pos p => Pos.pred_N p
  end.

(** ** The successor of a [N] can be seen as a [positive] *)

Definition succ_pos (n : N) : positive :=
 match n with
   | 0 => 1%positive
   | pos p => Pos.succ p
 end.

(** ** Addition *)

Definition add n m :=
  match n, m with
  | 0, _ => m
  | _, 0 => n
  | pos p, pos q => pos (p + q)
  end.

Infix "+" := add : N_scope.

(** Subtraction *)

Definition sub n m :=
match n, m with
| 0, _ => 0
| n, 0 => n
| pos n', pos m' =>
  match Pos.sub_mask n' m' with
  | IsPos p => pos p
  | _ => 0
  end
end.

Infix "-" := sub : N_scope.

(** Multiplication *)

Definition mul n m :=
  match n, m with
  | 0, _ => 0
  | _, 0 => 0
  | pos p, pos q => pos (p * q)
  end.

Infix "*" := mul : N_scope.

(** Order *)

Definition compare n m :=
  match n, m with
  | 0, 0 => Eq
  | 0, pos m' => Lt
  | pos n', 0 => Gt
  | pos n', pos m' => (n' ?= m')%positive
  end.

Infix "?=" := compare (at level 70, no associativity) : N_scope.

(** Boolean equality and comparison *)

Fixpoint eqb n m :=
  match n, m with
    | 0, 0 => true
    | pos p, pos q => Pos.eqb p q
    | _, _ => false
  end.

Definition leb x y :=
 match x ?= y with Gt => false | _ => true end.

Definition ltb x y :=
 match x ?= y with Lt => true | _ => false end.

Infix "=?" := eqb (at level 70, no associativity) : N_scope.
Infix "<=?" := leb (at level 70, no associativity) : N_scope.
Infix "<?" := ltb (at level 70, no associativity) : N_scope.

(** Min and max *)

Definition min n n' := match n ?= n' with
 | Lt | Eq => n
 | Gt => n'
 end.

Definition max n n' := match n ?= n' with
 | Lt | Eq => n'
 | Gt => n
 end.

(** Dividing by 2 *)

Definition div2 n :=
  match n with
  | 0 => 0
  | 1 => 0
  | pos (p~0) => pos p
  | pos (p~1) => pos p
  end.

(** Parity *)

Definition even n :=
  match n with
    | 0 => true
    | pos (xO _) => true
    | _ => false
  end.

Definition odd n := negb (even n).

(** Power *)

Definition pow n p :=
  match p, n with
    | 0, _ => 1
    | _, 0 => 0
    | pos p, pos q => pos (q^p)
  end.

Infix "^" := pow : N_scope.

(** Square *)

Definition square n :=
  match n with
    | 0 => 0
    | pos p => pos (Pos.square p)
  end.

(** Base-2 logarithm *)

Definition log2 n :=
 match n with
   | 0 => 0
   | 1 => 0
   | pos (p~0) => pos (Pos.size p)
   | pos (p~1) => pos (Pos.size p)
 end.

(** How many digits in a number ?
    Number 0 is said to have no digits at all.
*)

Definition size n :=
 match n with
  | 0 => 0
  | pos p => pos (Pos.size p)
 end.

Definition size_nat n :=
 match n with
  | 0 => O
  | pos p => Pos.size_nat p
 end.

(** Euclidean division *)

Fixpoint pos_div_eucl (a:positive)(b:N) : N * N :=
  match a with
    | xH =>
       match b with 1 => (1,0) | _ => (0,1) end
    | xO a' =>
       let (q, r) := pos_div_eucl a' b in
       let r' := double r in
       if b <=? r' then (succ_double q, r' - b)
        else (double q, r')
    | xI a' =>
       let (q, r) := pos_div_eucl a' b in
       let r' := succ_double r in
       if b <=? r' then (succ_double q, r' - b)
        else  (double q, r')
  end.

Definition div_eucl (a b:N) : N * N :=
  match a, b with
   | 0,  _ => (0, 0)
   | _, 0  => (0, a)
   | pos na, _ => pos_div_eucl na b
  end.

Definition div a b := fst (div_eucl a b).
Definition modulo a b := snd (div_eucl a b).

Infix "/" := div : N_scope.
Infix "mod" := modulo (at level 40, no associativity) : N_scope.

(** Greatest common divisor *)

Definition gcd a b :=
 match a, b with
  | 0, _ => b
  | _, 0 => a
  | pos p, pos q => pos (Pos.gcd p q)
 end.

(** Generalized Gcd, also computing rests of [a] and [b] after
    division by gcd. *)

Definition ggcd a b :=
 match a, b with
  | 0, _ => (b,(0,1))
  | _, 0 => (a,(1,0))
  | pos p, pos q =>
     let '(g,(aa,bb)) := Pos.ggcd p q in
     (pos g, (pos aa, pos bb))
 end.

(** Square root *)

Definition sqrtrem n :=
 match n with
  | 0 => (0, 0)
  | pos p =>
    match Pos.sqrtrem p with
     | (s, IsPos r) => (pos s, pos r)
     | (s, _) => (pos s, 0)
    end
 end.

Definition sqrt n :=
 match n with
  | 0 => 0
  | pos p => pos (Pos.sqrt p)
 end.

(** Operation over bits of a [N] number. *)

(** Logical [or] *)

Definition lor n m :=
 match n, m with
   | 0, _ => m
   | _, 0 => n
   | pos p, pos q => pos (Pos.lor p q)
 end.

(** Logical [and] *)

Definition land n m :=
 match n, m with
  | 0, _ => 0
  | _, 0 => 0
  | pos p, pos q => Pos.land p q
 end.

(** Logical [diff] *)

Fixpoint ldiff n m :=
 match n, m with
  | 0, _ => 0
  | _, 0 => n
  | pos p, pos q => Pos.ldiff p q
 end.

(** [xor] *)

Definition lxor n m :=
  match n, m with
    | 0, _ => m
    | _, 0 => n
    | pos p, pos q => Pos.lxor p q
  end.

(** Shifts *)

Definition shiftl_nat (a:N) := nat_rect _ a (fun _ => double).
Definition shiftr_nat (a:N) := nat_rect _ a (fun _ => div2).

Definition shiftl a n :=
  match a with
    | 0 => 0
    | pos a => pos (Pos.shiftl a n)
  end.

Definition shiftr a n :=
  match n with
    | 0 => a
    | pos p => Pos.iter div2 a p
  end.

(** Checking whether a particular bit is set or not *)

Definition testbit_nat (a:N) :=
  match a with
    | 0 => fun _ => false
    | pos p => Pos.testbit_nat p
  end.

(** Same, but with index in N *)

Definition testbit a n :=
  match a with
    | 0 => false
    | pos p => Pos.testbit p n
  end.

(** Translation from [N] to [nat] and back. *)

Definition to_nat (a:N) :=
  match a with
    | 0 => O
    | pos p => Pos.to_nat p
  end.

Definition of_nat (n:nat) :=
  match n with
    | O => 0
    | S n' => pos (Pos.of_succ_nat n')
  end.

(** Iteration of a function *)

Definition iter (n:N) {A} (f:A->A) (x:A) : A :=
  match n with
    | 0 => x
    | pos p => Pos.iter f x p
  end.

(** Conversion with a decimal representation for printing/parsing *)

Definition of_uint (d:Decimal.uint) := Pos.of_uint d.

Definition of_int (d:Decimal.int) :=
  match Decimal.norm d with
  | Decimal.Pos d => Some (Pos.of_uint d)
  | Decimal.Neg _ => None
  end.

Definition to_uint n :=
  match n with
  | 0 => Decimal.zero
  | pos p => Pos.to_uint p
  end.

Definition to_int n := Decimal.Pos (to_uint n).

End N.