Require Import Coq.Lists.List Bedrock.EqdepClass.
Require Export Coq.Classes.EquivDec.
Require Import Bedrock.Decidables.

Set Implicit Arguments.
Set Strict Implicit.

Section fin.
  Variable A : Type.

  Inductive fin : list A -> Type :=
  | FO : forall x ls, fin (x :: ls)
  | FS : forall x ls, fin ls -> fin (x :: ls).

  Fixpoint lift (ls : list A) e : fin ls -> fin (e ++ ls) :=
    match e as e return fin ls -> fin (e ++ ls) with
      | nil => fun x => x
      | a :: b => fun x => FS a (@lift ls b x)
    end.

  Definition finOut ls (f : fin ls) : match ls return fin ls -> Type with
                                        | nil => fun _ => Empty_set
                                        | _ => fun f => {f' : _ & f = FS _ f'} + {f = FO _ _}
                                      end f :=
  match f with
    | FO _ _ => inright _ (refl_equal _)
    | FS _ _ f' => inleft _ (existT _ f' (refl_equal _))
  end.

  Definition finIfz t (ls : list A) (d : fin (t :: ls))
    : forall (R : fin (t :: ls) -> Type) (h : R (@FO _ _)) (n : forall c, R (@FS _ _ c)),
    R d :=
    match d as d' in fin ls' return match ls' return fin ls' -> Type with
                                | nil => fun _ => Empty_set
                                | a :: b => fun d =>
                                  forall (R : fin (a :: b) -> Type) (h : R (@FO _ _)) (n : forall c, R (@FS _ _ c)), R d
                              end d'
      with
      | FO _ _ => fun _ h _ => h
      | FS _ _ x => fun _ _ f => f x
    end.

  Definition finArg ls (f : fin ls) : option (fin (tl ls)) :=
    match f with
      | FO _ _ => None
      | FS _ _ f' => Some f'
    end.

  Lemma fin_inj : forall z ls (x y : fin ls),
    x <> y
    -> FS z x <> FS z y.
    red; intros.
    assert (finArg (FS z x) = finArg (FS z y)) by congruence.
    simpl in *; congruence.
  Qed.

  Hint Immediate fin_inj.

  Definition finEq : forall ls (x y : fin ls), {x = y} + {x <> y}.
    refine (fix finEq ls : forall x y : fin ls, {x = y} + {x <> y} :=
      match ls return forall x y : fin ls, {x = y} + {x <> y} with
        | nil => fun x _ => match finOut x with end
        | _ :: _ => fun x y => match finOut x, finOut y with
                                 | inleft (existT x' _), inleft (existT y' _) => if finEq _ x' y' then left _ _ else right _ _
                                 | inright _, inright _ => left _ _
                                 | _, _ => right _ _
                               end
      end); clear finEq; (subst; auto; try congruence;
        match goal with
          | [ H : sigT _ |- _ ] => destruct H
        end; subst; discriminate).
  Defined.

  Global Instance EquivDec_fin ls : EqDec (fin ls) (@eq _) :=
  { equiv_dec := @finEq ls }.

  Definition dcomp_option T (a b : T) (d : dcomp a b) : option (a = b) :=
    match d with
      | Eq pf => Some pf
      | _ => None
    end.

  Global Instance Comparable_fin ls : Comparable (fin ls).
  constructor.
  refine ((fix finCmp ls (x : fin ls) : forall y : fin ls, dcomp x y :=
    match x in fin ls return forall y : fin ls, dcomp x y with
      | FO a b => fun y : fin (a :: b) =>
        @finIfz _ _ y (dcomp (FO a b)) (Eq (refl_equal _)) (fun _ => Lt _ _)
      | FS a ls r => fun y : fin (a :: ls) =>
        @finIfz _ _ y (dcomp (FS a r)) (Gt _ _)
          (fun r' => match finCmp _ r r' with
                       | Eq pf => Eq (match pf in _ = t return FS a r = FS a t with
                                        | refl_equal => refl_equal _
                                      end)

                       | Gt => Gt _ _
                       | Lt => Lt _ _
                     end)
    end) ls).
  Defined.

  Fixpoint get (ls : list A) : fin ls -> A :=
    match ls return fin ls -> A with
      | nil => fun f => match f in fin N return match N with
                                                  | nil => A
                                                  | _ => unit
                                                end with
                          | FO _ _ => tt
                          | FS _ _ _ => tt
                        end
      | x :: ls' => fun f => match f in fin N return match N with
                                                       | nil => Empty_set
                                                       | _ :: ls' => (fin ls' -> A) -> A
                                                     end with
                               | FO _ _ => fun _ => x
                               | FS _ _ f' => fun get_ls' => get_ls' f'
                             end (@get ls')
    end.

  Fixpoint liftD (ls : list A) e : forall i : fin ls, { x : fin (e ++ ls) & get x = get i } :=
    match e as e return forall i : fin ls, { x : fin (e ++ ls) & get x = get i } with
      | nil => fun x => existT _ x (refl_equal _)
      | a :: b => fun x =>
        match @liftD ls b x with
          | existT x pf =>
            existT _ (FS a x) (match pf in _ = t
                                 return get (FS a x) = t with
                                 | refl_equal => refl_equal _
                               end)
        end
    end.

  Fixpoint pf_list_simpl A b c (a : list A) : (a ++ b :: nil) ++ c = a ++ b :: c :=
    match a as a return (a ++ b :: nil) ++ c = a ++ b :: c with
      | nil => refl_equal (nil ++ b :: nil ++ c)
      | a' :: b' => match eq_sym (@pf_list_simpl A b c b') in _ = t return a' :: t = a' :: b' ++ b :: c
                      with
                      | refl_equal => refl_equal _
                    end
    end.

  Fixpoint fin_remove (U : Type) ls t ls' : forall (f : fin (ls ++ t :: ls')),
    (t = get f -> U) -> (forall f' : fin (ls ++ ls'), get f' = get f -> U) -> U :=
    match ls as ls
      return forall f : fin (ls ++ t :: ls'), (t = get f -> U) -> (forall f' : fin (ls ++ ls'), get f' = get f -> U) -> U
      with
      | nil => fun (f : fin (t :: ls')) =>
        match f in fin z
          return match z with
                   | nil => unit
                   | a :: b => (a = get f -> U) -> (forall f' : fin b, get f' = get f -> U) -> U
                 end
          with
          | FO _ _ => fun D _ => D refl_equal
          | FS _ _ f => fun _ F => F _ refl_equal
        end
      | a :: b => fun (f : fin (a :: b ++ t :: ls')) D F =>
        match finOut f with
          | inleft s =>
            @fin_remove _ _ _ _ (projT1 s)
              (match eq_sym (projT2 s) in _ = t' return (t = get t' -> U) -> (t = get (projT1 s)) -> U with
                 | refl_equal => fun x => x
               end D)
              (fun x' pf => F (FS _ x')
                match eq_sym (projT2 s) in _ = t return get (FS a x') = get t with
                  | refl_equal => pf
                end)
          | inright l => F (FO _ _) match eq_sym l in _ = t return get (FO _ _) = get t with
                                      | refl_equal => refl_equal
                                    end
        end
    end.

  Fixpoint fin_remove_range' (U : Type) ls'' ls' : forall (f : fin (ls'' ++ ls')),
    (forall x' : fin ls'', get x' = get f -> U) -> (forall f' : fin (ls'), get f' = get f -> U) -> U :=
    match ls'' as ls''
      return forall f : fin (ls'' ++ ls'), (forall x' : fin ls'', get x' = get f -> U) -> (forall f' : fin ls', get f' = get f -> U) -> U
      with
      | nil => fun (f : fin ls') => fun _ z => z f refl_equal
      | a :: b => fun (f : fin (a :: b ++  ls')) D F =>
        match finOut f with
          | inleft s =>
            @fin_remove_range' _ b ls' (projT1 s)
              (fun x' pf => D (FS _ x') match eq_sym (projT2 s) in _ = t return get (FS a x') = get t with
                                          | refl_equal => pf
                                        end)
              (fun x' pf => F x' match eq_sym (projT2 s) in _ = t return get x' = get t with
                                   | refl_equal => pf
                                 end)
          | inright l => D (FO _ _) match eq_sym l in _ = t return get (FO a b) = get t with
                                      | refl_equal => refl_equal
                                    end
        end
    end.

  Fixpoint fin_remove_range (U : Type) ls ls'' ls' : forall (f : fin (ls ++ ls'' ++ ls')),
    (forall x' : fin ls'', get x' = get f -> U) -> (forall f' : fin (ls ++ ls'), get f' = get f -> U) -> U :=
    match ls as ls
      return forall f : fin (ls ++ ls'' ++ ls'), (forall x' : fin ls'', get x' = get f -> U) -> (forall f' : fin (ls ++ ls'), get f' = get f -> U) -> U
      with
      | nil => fun (f : fin (ls'' ++ ls')) => @fin_remove_range' U ls'' ls' f
      | a :: b => fun (f : fin (a :: b ++ ls'' ++  ls')) D F =>
        match finOut f with
          | inleft s =>
            @fin_remove_range _ _ _ _ (projT1 s)
              (fun x' pf => D x' match eq_sym (projT2 s) in _ = t return get x' = get t with
                                   | refl_equal => pf
                                 end)
              (fun x' pf => F (FS _ x') match eq_sym (projT2 s) in _ = t return get (FS _ x') = get t with
                                          | refl_equal => pf
                                        end)
          | inright l => F (FO _ _)
              match eq_sym l in _ = t return get (FO _ _) = get t with
                | refl_equal => refl_equal
              end
        end
    end.

  Fixpoint liftDmid (ls ls' : list A) e : forall (i : fin (ls' ++ ls)),
    { x : fin (ls' ++ e ++ ls) & get x = get i }.
  refine (
    match ls' as ls' return forall (i : fin (ls' ++ ls)),
      { x : fin (ls' ++ e ++ ls) & get x = get i } with
      | nil => fun i => liftD e i
      | a :: b => fun i : fin (a :: b ++ ls) =>
        match finOut i with
          | inleft (existT r pf) =>
            match liftDmid ls b e r with
              | existT rr pf' =>
                @existT _ _ (FS a rr) _
            end
          | inright pf => @existT _ _ (FO _ _) _
        end
    end).
  rewrite pf; simpl; assumption.
  rewrite pf; reflexivity.
  Defined.

  Fixpoint liftDend (ls : list A) e (i : fin ls) :
    { x : fin (ls ++ e) & get x = get i } :=
    match i as i in fin ls return { x : fin (ls ++ e) & get x = get i } with
      | FO _ _ => existT _ (FO _ _) refl_equal
      | FS _ _ f =>
        match liftDend e f with
         | existT _ e => existT _ (FS _ _) e
        end
    end.

  Section liftD_Proofs.
    Variable EQ : EqDec A (@eq A).

    Lemma liftD_liftD_app : forall (a z y : list A) x0,
      projT1 (liftD y (projT1 (liftD a x0))) =
      match app_assoc_reverse y a z in (_ = t) return (fin t) with
        | eq_refl => projT1 (liftD (y ++ a) x0)
      end.
    Proof.
      induction y; simpl in *; uip_all.
        simpl in *. uip_all. reflexivity.
        simpl in *. case_eq (liftD y (projT1 (liftD a x0))).
        simpl. intros. assert (projT1 (liftD y (projT1 (liftD a x0))) = x).
        rewrite H; auto.
        rewrite IHy in H0. subst.
        destruct (liftD (y ++ a) x0). simpl. uip_all.
        generalize e e2. rewrite <- e2. uip_all. reflexivity.
    Qed.

    Lemma liftDmid_lift_nil : forall (a b : list A) x0,
      projT1 (liftDmid a b nil x0) = x0.
    Proof.
      induction b; simpl; intros; auto.
      destruct (finOut x0). destruct s. subst.
      specialize (IHb x). destruct (liftDmid a b nil x). simpl in *. subst; auto.

      subst. simpl. reflexivity.
    Qed.

    Lemma liftDmid_liftDmid_app : forall x y z a x0,
      projT1 (liftDmid (a ++ z) x y (projT1 (liftDmid z x a x0)))
      = match app_ass _ _ _ in _ = t return fin (_ ++ t) with
          | refl_equal => projT1 (liftDmid z x (y ++ a) x0)
        end.
    Proof.
      induction x.
        simpl; intros; apply liftD_liftD_app.
        intros. simpl in x0. destruct (finOut x0).

        destruct s. specialize (IHx y z a0 x1). subst. simpl in *.
        destruct (liftDmid z x a0 x1); simpl in *. destruct (liftDmid (a0 ++ z) x y x0); simpl in *.
        subst. destruct (liftDmid z x (y ++ a0) x1). simpl. uip_all. generalize e2 x2. rewrite e2.
        intros. rewrite (UIP_refl e3). reflexivity.

        subst; simpl. uip_all. generalize e. rewrite e. uip_all. reflexivity.
    Qed.
  End liftD_Proofs.

  Variable B : A -> Type.

  Inductive hlist : list A -> Type :=
  | HNil : hlist nil
  | HCons : forall x ls, B x -> hlist ls -> hlist (x :: ls).

  Definition hlist_hd (T : A) (ls : list A) (v : hlist (T :: ls)) : B T :=
    match v in hlist ls return match ls with
                                 | nil => unit
                                 | a :: _ => B a
                               end with
      | HNil => tt
      | HCons _ _ x _ => x
    end.

  Definition hlist_tl (T : A) (ls : list A) (v : hlist (T :: ls)) : hlist ls :=
    match v in hlist ls return match ls with
                                 | nil => unit
                                 | _ :: ls => hlist ls
                               end with
      | HNil => tt
      | HCons _ _ _ x => x
    end.

  Fixpoint hlist_app ll lr : hlist ll -> hlist lr -> hlist (ll ++ lr) :=
    match ll with
      | nil => fun _ x => x
      | _ :: _ => fun l r => HCons (hlist_hd l) (hlist_app (hlist_tl l) r)
    end.

  Fixpoint hlist_All ls (P : forall t, B t -> Prop) (h : hlist ls) {struct h} : Prop :=
    match h with
      | HNil => True
      | HCons _ _ a b => P _ a /\ hlist_All P b
    end.

  Variable dec : forall x (y z : B x), option (y = z).

  Definition hlistEq : forall x (y z : hlist x), option (y = z).
    refine (fix hlistEq x (y : hlist x) : forall z : hlist x, option (y = z) :=
      match y in hlist x return forall z : hlist x, option (y = z) with
        | HNil => fun z => match z in hlist x return match x return hlist x -> Type with
                                                       | nil => fun z => option (HNil = z)
                                                       | _ => fun _ => unit
                                                     end z with
                             | HNil => Some _
                             | _ => tt
                           end
        | HCons _ _ v1 y' => fun z => match z in hlist x return match x return hlist x -> Type with
                                                                  | nil => fun _ => unit
                                                                  | t :: x' => fun z => forall (v1 : B t) (y' : hlist x'),
                                                                    (forall v2, option (v1 = v2))
                                                                    -> (forall z', option (y' = z'))
                                                                    -> option (HCons v1 y' = z)
                                                                end z with
                                        | HNil => tt
                                        | HCons _ _ v2 z' => fun v1 _ dec' self => if dec' v2 then if self z' then Some _ else None else None
                                      end v1 y' (dec v1) (hlistEq _ y')
      end); clear hlistEq; abstract congruence.
  Defined.

  Variable cmp : forall x (y z : B x), dcomp y z.
  Definition hlistCmp : forall x (y z : hlist x), dcomp y z.
    refine (fix hlistCmp x (y : hlist x) : forall z : hlist x, dcomp y z :=
      match y in hlist x return forall z : hlist x, dcomp y z with
        | HNil => fun z => match z in hlist x return match x return hlist x -> Type with
                                                       | nil => fun z => dcomp HNil z
                                                       | _ => fun _ => unit
                                                     end z with
                             | HNil => Eq _
                             | _ => tt
                           end
        | HCons _ _ v1 y' => fun z => match z in hlist x return match x return hlist x -> Type with
                                                                  | nil => fun _ => unit
                                                                  | t :: x' => fun z => forall (v1 : B t) (y' : hlist x'),
                                                                    (forall v2, dcomp v1 v2)
                                                                    -> (forall z', dcomp y' z')
                                                                    -> dcomp (HCons v1 y') z
                                                                end z with
                                        | HNil => tt
                                        | HCons _ _ v2 z' => fun v1 _ cmp' self =>
                                          match cmp' v2 with
                                            | Eq _ =>
                                              match self z' with
                                                | Gt => Gt _ _
                                                | Lt => Lt _ _
                                                | Eq _ => Eq _
                                              end
                                            | Gt => Gt _ _
                                            | Lt => Lt _ _
                                          end
                                      end v1 y' (cmp v1) (hlistCmp _ y')
      end); clear hlistCmp; abstract congruence.
  Defined.

  Variable ocmp : forall x (y z : B x), option (dcomp y z).
  Fixpoint hlistOCmp x (y : hlist x) : forall (z : hlist x), option (dcomp y z).
    refine (
      match y as y in hlist x return forall z : hlist x, option (dcomp y z) with
        | HNil => fun z =>
          match z in hlist x return match x return hlist x -> Type with
                                      | nil => fun z => option (dcomp HNil z)
                                      | _ => fun _ => unit
                                    end z with
            | HNil => Some (Eq _)
            | _ => tt
          end
        | HCons _ _ v1 y' => fun z =>
          match z in hlist x return match x return hlist x -> Type with
                                      | nil => fun _ => unit
                                      | t :: x' => fun z => forall (v1 : B t) (y' : hlist x'),
                                        (forall v2, option (dcomp v1 v2))
                                        -> (forall z', option (dcomp y' z'))
                                        -> option (dcomp (HCons v1 y') z)
                                    end z with
            | HNil => tt
            | HCons _ _ v2 z' => fun v1 _ cmp' self =>
              match cmp' v2 with
                | None =>
                  match self z' with
                    | None => None
                    | Some Gt => Some (Gt _ _)
                    | Some Lt => Some (Lt _ _)
                    | Some (Eq _) => None
                  end
                | Some (Eq _) =>
                  match self z' with
                    | None => None
                    | Some Gt => Some (Gt _ _)
                    | Some Lt => Some (Lt _ _)
                    | Some (Eq _) => Some (Eq _)
                  end
                | Some Gt => Some (Gt _ _)
                | Some Lt => Some (Lt _ _)
              end
          end v1 y' (ocmp v1) (hlistOCmp _ y')
      end); clear hlistOCmp; abstract congruence.
  Defined.

  Fixpoint hlist_get (ls : list A) (i : fin ls) : hlist ls -> B (get i) :=
    match i in fin ls return hlist ls -> B (get i) with
      | FO _ _ => fun hl => hlist_hd hl
      | FS _ _ f' => fun hl => hlist_get f' (hlist_tl hl)
    end.

  Section hlist_Proofs.
    Variable EQ : EqDec A (@eq A).
    Lemma hlist_nil_only : forall (h : hlist nil),
      h = HNil.
    Proof.
      intros.
      change h with (match refl_equal in _ = t return hlist t with
                       | refl_equal => h
                     end).
      generalize (refl_equal (@nil A)). generalize h.
      assert (forall k (h : hlist k) (e : k = nil),
        match e in (_ = t) return (hlist t) with
          | eq_refl => h
        end = HNil).
      destruct h0.
      uip_all. reflexivity.
      congruence.
      eauto.
    Qed.

    Lemma hlist_eta : forall a b (h : hlist (a :: b)),
      h = HCons (hlist_hd h) (hlist_tl h).
    Proof.
      intros.
      assert (forall k (h : hlist k) (e : k = a :: b),
        match e in (_ = t) return (hlist t) with
          | eq_refl => h
        end = HCons (hlist_hd match e in _ = t return hlist t with
                                | eq_refl => h
                              end)
        (hlist_tl match e in _ = t return  hlist t with
                    | eq_refl => h
                  end)).
      destruct h0. congruence.
      intros. inversion e. subst.
      generalize e. uip_all. reflexivity.

      specialize (H _ h (refl_equal _)). assumption.
    Qed.

    Theorem hlist_get_lift : forall ls ls' ls'' (f : fin (ls ++ ls'')) G G' G'',
      hlist_get f (hlist_app G G'') =
      match liftDmid ls'' ls ls' f with
        | existT f' pf =>
          match pf in _ = t return B t with
            | refl_equal =>
              hlist_get f' (hlist_app G (hlist_app G' G''))
          end
      end.
    Proof.
      induction ls. simpl. intros. unfold liftDmid; simpl.
        Focus.
        generalize dependent ls'. induction ls'; simpl; auto.
          intros. specialize (IHls' (hlist_tl G')). rewrite IHls'. destruct (liftD ls' f).
          simpl. generalize (hlist_get x (hlist_app (hlist_tl G') G'')). generalize e. rewrite e.
          intros. rewrite (UIP_refl e0). reflexivity.

        intros. simpl in f. destruct (finOut f). destruct s; subst. simpl.
        specialize (@IHls ls' _ x (hlist_tl G) G' G''). rewrite IHls. clear IHls.
        destruct (liftDmid ls'' ls ls' x). reflexivity.
        subst. reflexivity.
    Qed.

    Theorem hlist_get_lift_end : forall ls' G' ls (f : fin ls) G,
      hlist_get f G =
      match liftDend ls' f with
        | existT f' pf =>
          match pf in _ = t return B t with
            | refl_equal =>
              hlist_get f' (hlist_app G G')
          end
      end.
    Proof.
      clear dec cmp ocmp.
      induction f; simpl; auto.
      destruct f; simpl in *. auto.
      intros. rewrite IHf. clear IHf. destruct (liftDend ls' f).
      generalize e. rewrite <- e. uip_all. auto.
    Qed.

    Lemma hlist_get_remove_range' : forall U a b (A : hlist a) (B' : hlist b) x P
      (D : forall x' : fin a, get x' = get x -> U) F,
      (forall x' (pf : get x' = get x),
        hlist_get x (hlist_app A B') =
          match pf in _ = z return B z with
            | refl_equal => hlist_get x' A
          end ->
        P (D x' pf)) ->
      (forall x' pf,
        hlist_get x (hlist_app A B') =
          match pf in _ = t return B t with
            | refl_equal => hlist_get x' B'
          end ->
        P (F x' pf)) ->
      P (@fin_remove_range' U a b x D F).
    Proof.
      clear dec cmp ocmp.
      induction a; simpl; intros; eauto.
      destruct (finOut x) as [ [ ? ? ] | ? ]; subst; simpl; eauto.
      eapply IHa; eauto.
    Qed.

    Theorem hlist_get_remove_range : forall U a b c (A : hlist a) (B' : hlist b) (C : hlist c) x P (D : forall x' : fin b, get x' = get x -> U) F,
      (forall x' (pf : get x' = get x),
        hlist_get x (hlist_app A (hlist_app B' C)) =
          match pf in _ = z return B z with
            | refl_equal => hlist_get x' B'
          end ->
        P (D x' pf)) ->
      (forall x' pf,
        hlist_get x (hlist_app A (hlist_app B' C)) =
          match pf in _ = t return B t with
            | refl_equal => hlist_get x' (hlist_app A C)
          end ->
        P (F x' pf)) ->
      P (@fin_remove_range U a b c x D F).
    Proof.
      clear dec cmp ocmp.
      induction a; simpl; intros.
      eapply hlist_get_remove_range'; eauto.
      destruct (finOut x); subst; simpl.
        destruct s; subst; simpl. eapply IHa; eauto.
        eapply X0. auto.
    Qed.

  End hlist_Proofs.

  Fixpoint absAll (ls : list A) :
    (hlist ls -> Type) -> Type :=
    match ls return (hlist ls -> Type) -> Type with
      | nil => fun R => R (HNil)
      | a :: b => fun R =>
        forall x : B a, absAll (fun y => R (HCons x y))
    end.

  Fixpoint hlistDestruct (ls : list A) (args : hlist ls) {struct args}
    : forall K : hlist ls -> Type, absAll K -> K args :=
      match
        args as args0 in hlist ls0
          return (forall K : hlist ls0 -> Type, absAll K -> K args0)
        with
        | HNil =>
          fun (K : hlist nil -> Type) (cc : absAll K) => cc
        | HCons x0 ls0 x args =>
          fun (K : hlist (x0 :: ls0) -> Type) (cc : absAll K) =>
            hlistDestruct args
            (fun y : hlist ls0 => K (HCons x y))
            (cc x)
      end.

  Variable a : A.
  Variable b : B a.
  Fixpoint hlistIn (ls : list A) : hlist ls -> Prop :=
    match ls as ls return hlist ls -> Prop with
      | nil => fun _ => False
      | hd :: tl => fun hl =>
        (exists pf : a = hd, hlist_hd hl = match pf in _ = t return B t with
                                             | refl_equal => b
                                           end)
        \/ hlistIn (hlist_tl hl)
    end.

End fin.

Implicit Arguments FO [A x ls].
Implicit Arguments FS [A x ls].
Implicit Arguments finIfz [A t ls].

Implicit Arguments get [A].
Implicit Arguments HNil [A B].
Implicit Arguments HCons [A B x ls].

Section hlist_map.
  Variable A : Type.
  Variable F : A -> Type.
  Variable G : A -> Type.
  Variable ff : forall x, F x -> G x.

  Fixpoint hlist_map (ls : list A) (hl : hlist F ls) {struct hl} : hlist G ls :=
    match hl in @hlist _ _ ls return hlist G ls with
      | HNil => HNil
      | HCons _ _ hd tl =>
        HCons (ff hd) (hlist_map tl)
    end.
End hlist_map.

Section hlist_fold2.
  Variables T U V : Type.
  Variables F G : T -> Type.
  Variable f : U -> forall t : T, F t -> G t -> U.

  Fixpoint hlist_fold2 ls (l : hlist F ls) {struct l} : hlist G ls -> U -> U :=
    match l in hlist _ ls
      return hlist G ls -> U -> U
      with
      | HNil => fun _ acc => acc
      | HCons _ _ fr hr => fun r acc =>
        hlist_fold2 hr (hlist_tl r) (f acc fr (hlist_hd r))
    end.
End hlist_fold2.

Export Decidables.


Require Export SfLib.

Definition relation (X:Type) := X -> X -> Prop.

Definition partial_function {X : Type} (R : relation X) :=
  forall (x y1 y2 : X),
    R x y1 -> R x y2 -> y1 = y2.

Theorem next_nat_partial_function :
  partial_function next_nat.
  unfold partial_function.
  intros x y1 y2.
  intros h1 h2.
  inversion h1.
  inversion h2.
  reflexivity.
Qed.

Theorem le_nat_a_partial_function :
  ~(partial_function le).
  unfold not.
  intros h.
  unfold partial_function in h.
  assert (0 = 1).
  apply h with (x:= 0).
  apply le_n.
  apply le_S.
  apply le_n.
  inversion H.
Qed.

Definition reflexive {X : Type} (R : relation X) :=
  forall a : X, R a a.

Definition transitive {X : Type} (R : relation X) :=
  forall a b c : X, R a b -> R b c -> R a c.

Theorem lt_trans' :
  transitive lt.
  unfold transitive.
  intros a b c h1 h2.
  unfold lt in h1.
  unfold lt in h2.
  unfold lt.
  induction h2.
  apply le_S.
  apply h1.
  apply le_S.
  apply IHh2.
Qed.

Theorem le_S_n:
  forall n m ,
    S n <= S m ->
    n <= m.
  intros n m h.
  generalize dependent n.
  induction m.
  intros n h1.
  inversion h1.
  apply le_n.
  inversion H0.
  intros n h1.
  inversion h1.
  apply le_n.
  apply le_S.
  apply IHm.
  apply H0.
Qed.

Theorem le_Sn_n_inf:
  forall n, ~(S n <= n).
  induction n.
  intros h.
  inversion h.
  unfold not in IHn.
  intros h.
  apply le_S_n in h.
  apply IHn in h.
  apply h.
Qed.

Definition symmetric {X : Type} (R : relation X) :=
  forall a b : X, (R a b) -> (R b a).

Theorem le_not_symm :
  ~(symmetric le).
  intros h.
  unfold symmetric in h.
  assert (0 <= 1).
  apply le_S.
  apply le_n.
  apply h in H.
  inversion H.
Qed.

Theorem le_Sn_m_n_m' :
  forall n m,
    S n <= m -> n <= m.
  intros n m h1.
  assert (n <= S n).
  apply le_S.
  apply le_n.
  Check le_trans.
  apply (le_trans n (S n) m H h1).
Qed.
  Theorem le_trans :
  transitive le.
  unfold transitive.
  intros a b c h1 h2.
  induction h2.
  apply h1.
  apply le_S.
  apply IHh2.
Qed.
Theorem le_Sn_Sm_n_m' :
  forall n m,
    S n <= S m -> n <= m.
  intros n m h1.
  inversion h1.
  apply le_n.
  apply le_Sn_m_n_m'.
  apply H0.
Qed.

Definition antisymmetric {X:Type} (R:relation X) :=
  forall a b: X,
    (R a b) -> (R b a) -> a = b.

Inductive refl_step_closure {X : Type} (R:relation X) : relation X :=
| rsc_refl : forall (x:X), refl_step_closure R x x
| rsc_step : forall (x y z : X),
               R x y -> refl_step_closure R y z -> refl_step_closure R x z.

Theorem rsc_R :
  forall (X:Type) (R:relation X) (x y : X),
    R x y -> refl_step_closure R x y.
  intros X R x y h.
  apply (rsc_step R x y y h (rsc_refl R y)).
Qed.

Theorem rsc_trans:
  forall (X:Type) (R:relation X) (x y z : X),
    refl_step_closure R x y ->
    refl_step_closure R y z ->
    refl_step_closure R x z.
  intros X R x y z.
  intros h1.
  generalize dependent z.
  induction h1.
  intros z h1.
  apply h1.
  intros z0 h2.
  apply IHh1 in h2.
  apply rsc_step with y.
  apply H.
  apply h2.
Qed.

Print rsc_trans.

Theorem bbbbbbbbcj:
  forall (X : Type) (x y : X)(a b : nat)(R: relation X),
    refl_step_closure R x y -> a + b = b + a.
  intros X x y a b R h.
  induction h.


Require Import Reals.
Local Open Scope R_scope.
From ValidSDP Require Import validsdp.

Let p (x0 x1 x2 x3 x4 x5 : R) :=
  - 4/1
  * (x3 * x3 * x0
     + 8/1 * (x4 - x5) * (x1 - x2)
       - x3 * (16/1 * x0 + (x4 - 8/1) * x1 + (x5 - 8/1) * x2)).

Let b1 (x0 x1 x2 x3 x4 x5 : R) :=
  (x0 - 1) * (117547965573/100000000000 - x0).

Let b2 (x0 x1 x2 x3 x4 x5 : R) :=
  (x1 - 1) * (117547965573/100000000000 - x1).

Let b3 (x0 x1 x2 x3 x4 x5 : R) :=
  (x2 - 1) * (117547965573/100000000000 - x2).

Let b4 (x0 x1 x2 x3 x4 x5 : R) :=
  (x3 - 251952632905/100000000000) * (90601/10000 - x3).

Let b5 (x0 x1 x2 x3 x4 x5 : R) :=
  (x4 - 4/1) * (63504/10000 - x4).

Let b6 (x0 x1 x2 x3 x4 x5 : R) :=
  (x5 - 625/100) * (1553/100 - x5).

Theorem p_nonneg (x0 x1 x2 x3 x4 x5 : R) :
  b1 x0 x1 x2 x3 x4 x5 >= 0 ->
  b2 x0 x1 x2 x3 x4 x5 >= 0 ->
  b3 x0 x1 x2 x3 x4 x5 >= 0 ->
  b4 x0 x1 x2 x3 x4 x5 >= 0 ->
  b5 x0 x1 x2 x3 x4 x5 >= 0 ->
  b6 x0 x1 x2 x3 x4 x5 >= 0 ->
  p x0 x1 x2 x3 x4 x5 >= 0.
Proof.
unfold b1, b2, b3, b4, b5, b6, p.
validsdp.
Qed.


(*|
#######################################
Inductively defined dense vector lemmas
#######################################

:Link: https://stackoverflow.com/q/31111114
|*)

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

Inspired by another question on StackOverflow, I defined a *dense
vector* to be a vector with ``option A`` type elements that only
contains ``Some _`` elements, and no ``None`` elements.
|*)

Require Import Vector.

Section Dense.
  Variable A : Type.

  Inductive Is_dense : forall n, t (option A) n -> Prop :=
  | snil : Is_dense 0 (nil _)
  | scons: forall n s, Is_dense n s ->
                       forall a, Is_dense (S n) (cons _ (Some a) _ s).

(*| How can I prove the following two lemmas? |*)

  Lemma Is_dense_tl : forall n (s : t (option A) (S n)),
      Is_dense (S n) s -> Is_dense n (tl s).
  Abort. (* .none *)

(*| and |*)

  Lemma dense_hd : forall n (s : t (option A) (S n)), Is_dense (S n) s -> A.
  Abort. (* .none *)

(*|
And also, in the first lemma, when I do ``inversion s.`` I get the
elements ``h n' X`` that were used by ``s``'s constructor, but how can
I get an equality stating ``s = cons (option A) h n' X``?
|*)

(*|
Answer
******

Because of type dependency, ``inversion`` can't directly generate what
you expect, because it is not true in general. However, it is true for
a large family of types, whose equality is *decidable*. In your case,
you can apply ``Eqdep_dec.inj_pair2_eq_dec`` to get the equality you
want, if you provide the fact that equality upon ``nat`` is decidable
(and it is).

Here is the proof for the first lemma:
|*)
  Lemma Is_dense_tl : forall n (s : t (option A) (S n)),
      Is_dense (S n) s -> Is_dense n (tl s).
  Proof.
    intros n s hs.
    inversion hs. subst. clear hs.
    apply Eqdep_dec.inj_pair2_eq_dec in H0.
    - now rewrite <- H0.
    - (* insert proof of decidablity *) admit.
  Admitted.

(*|
EDIT: About your comment about the second lemma.

The main difference between your two lemmas is that the first one
tries to prove the property ``Is_dense n (tl s)`` which lives in
``Prop``, whereas the second one tries to exhibit a term of type
``A``. In short, the former creates a term of sort ``Prop``, the
latter a term of sort ``Type``.

To avoid inconsistency in Coq's logic, there is a *hierarchy* to
organize the sorts, which is (not exactly, but to give you the rough
idea) ``Prop : Set`` ``Set : Type_0`` and ``Type_n : Type_n+1``. On
top of this hierarchy is built a type system where the dependent pair
(e.g. the type ``{n : nat | even n}`` is the type of even natural
numbers) is restricted. You can build a ``Prop`` from other ``Prop``
(e.g. ``forall p : Prop, p -> p`` lives in ``Prop``). However you need
to be careful when ``Type`` is involved. For example, (again, please
refer to Coq's documentation for the exact statement) ``forall n :
Type_i, Type_j`` is of type ``Type_max(i, j)``.

This restriction is here to avoid inconsistency (like Russel's
paradox) in Coq's type system.

In your case, you are trying to inspect (using ``inversion``) a term
of sort ``Prop`` (``Is_dense (S n) s``) to build a term of type ``A``,
of sort ``Type``. This is forbidden by the type system. To build a
term of sort ``Type``, you need to inspect terms of at least the sort
``Set``. In your example, all you have to do is change the definition
of ``Is_dense`` to land in ``Type`` instead of ``Prop``, and you're
good to go.

----

**Q:** It needed a decidability proof for ``nat``, rather than for
``A``, so that was easy, using ``Arith.Peano_dec.eq_nat_dec``.
However, when I try to use ``inversion hs.`` for the second lemma, I
get the error ``Error: Inversion would require case analysis on sort
Type which is not allowed for inductive definition Is_dense.`` Why is
it possible to use inversion in the first lemma but not in the second?

**Q:** After changing ``A`` from ``Type`` to ``Set``, and chaning
``Is_dense ...`` from ``Prop`` to ``Set`` I was able to do ``inversion
hs.`` in the second lemma. What happened? Is there a less drastic
solution (than changing the definitions)?
|*)


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Eval compute in (next_weekday friday).
   (* ==> monday : day *)
Eval compute in (next_weekday (next_weekday saturday)).
   (* ==> tuesday : day *)

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

(** The keyword [compute] tells Coq precisely how to
    evaluate the expression we give it.  For the moment, [compute] is
    the only one we'll need; later on we'll see some alternatives that
    are sometimes useful. *)

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

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

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

Proof. simpl. reflexivity.  Qed.

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

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

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

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

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

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

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

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

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

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

(** The last two illustrate the syntax for multi-argument
    function definitions. *)

(** The following four "unit tests" constitute a complete
    specification -- a truth table -- for the [orb] function: *)

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

(** (Note that we've dropped the [simpl] in the proofs.  It's not
    actually needed because [reflexivity] automatically performs
    simplification.) *)

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

(** The values [Admitted] and [admit] can be used to fill
    a hole in an incomplete definition or proof.  We'll use them in the
    following exercises.  In general, your job in the exercises is
    to replace [admit] or [Admitted] with real definitions or proofs. *)

(** **** Exercise: 1 star (nandb)  *)
(** Complete the definition of the following function, then make
    sure that the [Example] assertions below can each be verified by
    Coq.  *)

(** This function should return [true] if either or both of
    its inputs are [false]. *)

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

(** Remove "[Admitted.]" and fill in each proof with
    "[Proof. reflexivity. Qed.]" *)

Example test_nandb1:               (nandb true false) = true.
Proof. reflexivity.  Qed.
Example test_nandb2:               (nandb false false) = true.
Proof. reflexivity.  Qed.
Example test_nandb3:               (nandb false true) = true.
Proof. reflexivity.  Qed.
Example test_nandb4:               (nandb true true) = false.
Proof. reflexivity.  Qed.
(** [] *)

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

Definition andb3 (b1:bool) (b2:bool) (b3:bool) : bool :=
  match b1, b2, b3 with
    | true, true, true => true
    | _, _, _ => false
  end.

Example test_andb31:                 (andb3 true true true) = true.
Proof. reflexivity.  Qed.
Example test_andb32:                 (andb3 false true true) = false.
Proof. reflexivity.  Qed.
Example test_andb33:                 (andb3 true false true) = false.
Proof. reflexivity.  Qed.
Example test_andb34:                 (andb3 true true false) = false.
Proof. reflexivity.  Qed.
(** [] *)

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

(** The [Check] command causes Coq to print the type of an
    expression.  For example, the type of [negb true] is [bool]. *)

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

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

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

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

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

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

Module Playground1.

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

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

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

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

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

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

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

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

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

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

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

End Playground1.

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

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

Check (S (S (S (S O)))).
Eval compute in (minustwo 4).

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

Check S.
Check pred.
Check minustwo.

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

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

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

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

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

Example test_oddb1:    (oddb (S O)) = true.
Proof. reflexivity.  Qed.
Example test_oddb2:    (oddb (S (S (S (S O))))) = false.
Proof. reflexivity.  Qed.

(** Naturally, we can also define multi-argument functions by
    recursion.  (Once again, we use a module to avoid polluting the
    namespace.) *)

Module Playground2.

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

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

Eval compute in (plus (S (S (S O))) (S (S O))).

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

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

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

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

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

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

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

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

End Playground2.

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

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

Fixpoint factorial (n:nat) : nat :=
  match n with
    | 0 => S 0
    | S n => mult (S n) (factorial n)
  end.

Example test_factorial1:          (factorial 3) = 6.
Proof. reflexivity. Qed.
Example test_factorial2:          (factorial 5) = (mult 10 12).
Proof. reflexivity. Qed.

(** [] *)

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

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

Check ((0 + 1) + 1).

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

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

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

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

(** Similarly, the [ble_nat] function tests [nat]ural numbers for
    [l]ess-or-[e]qual, yielding a [b]oolean. *)

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

Example test_ble_nat1:             (ble_nat 2 2) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat2:             (ble_nat 2 4) = true.
Proof. reflexivity.  Qed.
Example test_ble_nat3:             (ble_nat 4 2) = false.
Proof. reflexivity.  Qed.

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

Definition blt_nat (n m : nat) : bool :=
  andb (ble_nat n m) (negb (beq_nat n m)).

Example test_blt_nat1:             (blt_nat 2 2) = false.
Proof. reflexivity. Qed.
Example test_blt_nat2:             (blt_nat 2 4) = true.
Proof. reflexivity. Qed.
Example test_blt_nat3:             (blt_nat 4 2) = false.
Proof. reflexivity. Qed.

(** [] *)

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

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

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

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

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

(** (_Note_: You may notice that the above statement looks
    different in the original source file and the final html output. In Coq
    files, we write the [forall] universal quantifier using the
    "_forall_" reserved identifier. This gets printed as an
    upside-down "A", the familiar symbol used in logic.)  *)

(** The form of this theorem and proof are almost exactly the
    same as the examples above; there are just a few differences.

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

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

    The keywords [intros], [simpl], and [reflexivity] are examples of
    _tactics_.  A tactic is a command that is used between [Proof] and
    [Qed] to tell Coq how it should check the correctness of some
    claim we are making.  We will see several more tactics in the rest
    of this lecture, and yet more in future lectures. *)

(** We could try to prove a similar theorem about [plus] *)

Theorem plus_n_O : forall n, n + 0 = n.

(** However, unlike the previous proof, [simpl] doesn't do anything in
    this case *)

Proof.
  simpl. (* Doesn't do anything! *)
Abort.

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

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

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

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

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

(** Here is a slightly more interesting theorem: *)

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

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

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

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

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

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

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

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

Theorem plus_id_exercise : forall n m o : nat,
  n = m -> m = o -> n + m = m + o.
Proof.
  intros n m o.
  intros H1.
  intros H2.
  rewrite -> H1.
  rewrite -> H2.
  reflexivity. Qed.

(** [] *)

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

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

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

(** **** Exercise: 2 stars (mult_S_1)  *)
Theorem mult_S_1 : forall n m : nat,
  m = S n ->
  m * (1 + n) = m * m.
Proof.
  intros n m.
  intros H.
  rewrite -> H.
  reflexivity. Qed.
(** [] *)

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

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

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

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

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

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

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

(** The [destruct] generates _two_ subgoals, which we must then
    prove, separately, in order to get Coq to accept the theorem as
    proved.  (No special command is needed for moving from one subgoal
    to the other.  When the first subgoal has been proved, it just
    disappears and we are left with the other "in focus.")  In this
    proof, each of the subgoals is easily proved by a single use of
    [reflexivity].

    The annotation "[as [| n']]" is called an _intro pattern_.  It
    tells Coq what variable names to introduce in each subgoal.  In
    general, what goes between the square brackets is a _list_ of
    lists of names, separated by [|].  Here, the first component is
    empty, since the [O] constructor is nullary (it doesn't carry any
    data).  The second component gives a single name, [n'], since [S]
    is a unary constructor.

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

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

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

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

(** [] *)

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

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

Theorem identity_fn_applied_twice :
  forall (f : bool -> bool),
  (forall (x : bool), f x = x) ->
  forall (b : bool), f (f b) = b.
Proof.
  intros f.
  intros H.
  intros b.
  rewrite -> H.
  rewrite -> H.
  reflexivity.
Qed.

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

Theorem negation_fn_applied_twice :
  forall (f : bool -> bool),
    (forall (x : bool), f x = negb x) ->
    forall (b : bool), f (f b) = b.
Proof.
  intros f.
  intros H.
  intros b.
  rewrite -> H.
  rewrite -> H.
  rewrite -> negb_involutive.
  reflexivity.
Qed.

(** [] *)

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

Theorem orb_true_c :
  forall (c : bool),
    orb true c = true.
Proof.
  intros c.
  destruct c.
  reflexivity.
  reflexivity.
Qed.

Theorem orb_c_true :
  forall (c : bool),
    orb c true = true.
Proof.
  intros c.
  destruct c.
  reflexivity.
  reflexivity.
Qed.

Theorem andb_c_false :
  forall (c : bool),
    andb c false = false.
Proof.
  intros c.
  destruct c.
  reflexivity.
  reflexivity.
Qed.

Theorem andb_true_c :
  forall (c : bool),
    andb true c = c.
Proof.
  intros c.
  destruct c.
  reflexivity.
  reflexivity.
Qed.

Theorem andb_orb_true :
  forall (c : bool),
  (andb true c = orb true c) ->
  c = true.
Proof.
  intros c.
  rewrite -> orb_true_c.
  rewrite -> andb_true_c.
  destruct c.
  reflexivity.
  discriminate.
Qed.

Theorem andb_orb_false :
  forall (c : bool),
  (andb false c = orb false c) ->
  c = false.
Proof.
  intros c.
  destruct c.
  intros H.
  discriminate.
  intros H.
  reflexivity.
Qed.

Theorem andb_eq_orb :
  forall (b c : bool),
  (andb b c = orb b c) ->
  b = c.
Proof.
  intros b.
  destruct b.
  intros c.
  intros H.
  rewrite -> andb_orb_true.
  reflexivity.
  rewrite -> H.
  reflexivity.
  intros c.
  intros H.
  rewrite -> andb_orb_false.
  reflexivity.
  rewrite -> H.
  reflexivity.
Qed.

(** [] *)

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

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

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

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

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

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

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

Inductive bin : Type :=
| B : bin
| D : bin -> bin
| M : bin -> bin.

Fixpoint incr (n : bin) : bin :=
  match n with
    | B => M B
    | D n' => M n'
    | M n' => D (incr n')
  end.

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

Fixpoint bin_to_nat (n : bin) : nat :=
  match n with
    | B => O
    | D n' => double (bin_to_nat n')
    | M n' => S (double (bin_to_nat n'))
  end.

Theorem bin_comm :
  forall n : bin,
    bin_to_nat(incr n) = S (bin_to_nat n).
Proof.
  intros n.
  induction n.
  reflexivity.
  reflexivity.
  simpl.
  rewrite -> IHn.
  reflexivity.
Qed.

(* ###################################################################### *)
(** * More on Notation (Advanced) *)

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

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

(** For each notation-symbol in Coq we can specify its _precedence level_
    and its _associativity_. The precedence level n can be specified by the
    keywords [at level n] and it is helpful to disambiguate
    expressions containing different symbols. The associativity is helpful
    to disambiguate expressions containing more occurrences of the same
    symbol. For example, the parameters specified above for [+] and [*]
    say that the expression [1+2*3*4] is a shorthand for the expression
    [(1+((2*3)*4))]. Coq uses precedence levels from 0 to 100, and
    _left_, _right_, or _no_ associativity.

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

    Notation scopes also apply to numeral notation (3,4,5, etc.), so you
    may sometimes see [0%nat] which means [O], or [0%Z] which means the
    Integer zero.
*)

(** * [Fixpoint] and Structural Recursion (Advanced) *)

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

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

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

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

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

(** $Date: 2014-12-31 15:31:47 -0500 (Wed, 31 Dec 2014) $ *)


Set Implicit Arguments.

Require Import
        Discrete.DiscreteType
        Finite.FinType
        Tactics.Tactics.

Import ListNotations.

Fixpoint to_sigma_list (A : Type) (f : A -> finType) (xs : list A) : list (sigT f) :=
  match xs with
  | [] => []
  | x :: xs' => (map (existT f x) (elem (f x))) ++ to_sigma_list f xs'
  end.

Lemma count_map_existT
      (A : discType)
      (f : A -> discType)
      (x : A)(xs : list (f x))(y : f x)
  : count (map (existT f x) xs) (existT f x y) = count xs y.
Proof.
  induction xs as [| x' xs] ; crush.
  -
    dec ; auto.
    +
      contradict n. exact (sigT_proj2_fun _ e).
    +
      subst x'. contradict n. reflexivity.
Qed.

Lemma count_map_existT_zero
      (A : discType)
      (f : A -> discType)
      (x x' : A) (xs : list (f x)) (y : f x')
  : x <> x' -> count (map (existT f x) xs) (existT f x' y) = 0.
Proof.
  intros E. induction xs as [| x1 xs] ; repeat (crush ; dec).
Qed.

Lemma to_sigma_list_count
      (A : discType)
      (f : A -> finType)
      (xs : list A)
      (s: sigT f)
  : count (to_sigma_list f xs) s = count xs (projT1 s).
Proof.
  induction xs as [| x xs] ; crush.
  -
    destruct s. cbn in *.
    rewrite count_app. rewrite IHxs. dec.
    + change (S (count xs x)) with (1 + count xs x). f_equal. subst x.
      rewrite (@count_map_existT _ f _ (elem (f _)) _).
      unfold elem. rewrite enum_sound. crush.
    +
      change (count xs x) with (0 + (count xs x)). f_equal.
      rewrite (@count_map_existT_zero _ f _ _); auto.
Qed.

Lemma sigma_enum_sound
      (A : finType)
      (f : A -> finType)
      (s : sigT f)
  : count (to_sigma_list f (elem A)) s = 1.
Proof.
  rewrite to_sigma_list_count. now pose proof (enum_sound (projT1 s)).
Qed.

Instance FinTypeC_sigma (A : finType) (f : A -> finType): FinTypeC (DiscSigT f).
Proof.
  econstructor.  apply sigma_enum_sound.
Defined.

Canonical Structure FinType_sigma (A : finType) (f : A -> finType) :=
  FinType (DiscSigT f).


(** * Boundedness *)

From DEZ Require Export
  Init.

(** ** Lower Bound *)

Class IsLowerBnd (A : Type) (X : A -> A -> Prop)
  (x : A) : Prop :=
  lower_bnd (y : A) : X x y.

(** ** Upper Bound *)

Class IsUpperBnd (A : Type) (X : A -> A -> Prop)
  (x : A) : Prop :=
  upper_bnd (y : A) : X y x.

Section Context.

Context (A : Type) (X : A -> A -> Prop)
  (x : A).

(** A lower bound with respect to a binary relation is a special case
    of an upper bound with respect to its flipped version. *)

#[local] Instance lower_bnd_is_upper_bnd_flip
  `{!IsLowerBnd X x} : IsUpperBnd (flip X) x.
Proof. intros y. unfold flip in *. eauto. Qed.

#[local] Instance upper_bnd_flip_is_lower_bnd
  `{!IsUpperBnd (flip X) x} : IsLowerBnd X x.
Proof. intros y. unfold flip in *. eauto. Qed.

End Context.

(** ** Bounded *)

Class IsBnd (A : Type) (X : A -> A -> Prop)
  (x y : A) : Prop := {
  bnd_is_lower_bnd :> IsLowerBnd X x;
  bnd_is_upper_bnd :> IsUpperBnd X y;
}.


(* begin hide *)
Require Import List.
Require Import FingerTree.Monoid.
Require Import FingerTree.DependentFingerTree.
Require Import Coq.Program.Program Coq.Program.Equality.
Require Import Omega.
Implicit Type v A : Type.
Set Implicit Arguments.
Unset Standard Proposition Elimination Names.

Implicit Arguments fingertree [[mono] [ma]].
(* end hide *)
(** printing lparr $\coqdoublebar$ *)(** printing rparr $\coqdoublebar$ *)(** printing cdot $\cdot$ *)(** printing epsilon $\varepsilon$ *)(** printing +:+ $\treeapp$ *)(** printing ++ $\app$ *)(** printing := $\coloneqq$ *)(** printing :> $\Yright$ *)(** printing < $<$ *)(** printing > $>$ *)
(** ** Une interface non dépendante
   %\label{fts:inst:fingertree}%

   Comme décrit précédemment, on peut agréger la mesure et le [fingertree] dans une paire dépendante pour
   donner une interface simplifiée aux %\FTs% dépendants. *)

Section FingerTree.
  Context `(ma : Measured v A).
  Definition FingerTree := { m : v & fingertree v A m }.
  Notation " ts :| t " := (existT _ ts t) (at level 20).

  (** Cela nous donne un type [FingerTree v {mono} A {ma}], qu'on peut comparer au type
     original %\ind{FingerTree} \id{v} \id{a}% dans %\Haskell%. On a ajouté l'implémentation [monoid] et la
     fonction de mesure [ma] comme paramètres explicites alors qu'en %\Haskell% ils sont passés
     implicitement à l'aide des classes de type à chaque fonction les manipulant.

     *)
  (* begin hide *)
  (** Now we can wrap all the operations on [fingertree] objects. *)
  Program Definition empty : FingerTree := ε :| Empty.

  Program Definition is_empty (s : FingerTree) : Prop :=
    let 'ts :| t := s in isEmpty t.

  Program Definition is_empty_dec (s : FingerTree)
    : {is_empty s} + {~is_empty s} :=
    let 'ts :| t := s in
    if isEmpty_dec t then left _ else right _.

  Program Definition singleton (x : A) : FingerTree :=
    _ :| Single x.

  Program Definition cons (x : A) (s : FingerTree) : FingerTree :=
    let 'ts :| t := s in _ :| add_left x t.

  Program Definition snoc (s : FingerTree) (x : A) : FingerTree :=
    let '_ :| t := s in _ :| add_right t x.

  Program Definition head (s : FingerTree | ~ is_empty s) : A :=
    let '_ :| t := s in head t.

  Program Definition last (s : FingerTree | ~ is_empty s) : A :=
    let '_ :| t := s in last t.

  Program Definition tail (s : FingerTree | ~ is_empty s) : FingerTree :=
    let '_ :| t := s in tail t.

  Program Definition liat (s : FingerTree | ~ is_empty s) : FingerTree :=
    let '_ :| t := s in liat t.

  Definition tree_measure (s : FingerTree) : v :=
    let 'ts :| _ := s in ts.

  Require Import JMeq.

  (* end hide *)
  (** On ne décrit pas le "repackaging" en détail, il s'agit just de décomposer un objet de type
     [FingerTree], appeler la fonction appropriée sur les [fingertree] et recomposer la paire dépendante.
     En revanche un point important est que l'on peut exporter les vues sur les [fingertree] et retrouver
     la mesure associée: *)

  Program Definition tree_size (s : FingerTree) : nat :=
    let '_ :| t := s in tree_size t.

  Inductive left_view : Type :=
  | nil_left : left_view | cons_left : A -> FingerTree -> left_view.
  (* begin hide *)
  Program Definition view_left (s : FingerTree) : left_view :=
    let '_ :| t := s in
    match view_L t with
      | nil_L => nil_left
      | cons_L x ts t => cons_left x (ts :| t)
    end.
  (* end hide *)

  Lemma view_left_size : forall t x t', view_left t = cons_left x t' ->
    tree_size t' < tree_size t.
  Proof.
    intros.
    destruct t ; destruct t' ; simpl in *.
    generalize H ; clear H.
    remember (view_L f) as vf.
    destruct vf ; simpl in * ; intros ; try discriminate.
    symmetry in Heqvf.
    pose (view_L_size_measure f Heqvf).
    inversion H.
    subst.
    assert(Hi:=inj_pairT2 H3).
    subst f0.
    simpl.
    omega.
  Qed.
  (* begin hide *)
  Inductive right_view : Type :=
  | nil_right : right_view
  | cons_right : FingerTree -> A -> right_view.

  Program Definition view_right (s : FingerTree) : right_view :=
    let '_ :| t := s in
    match view_R t with
      | nil_R => nil_right
      | cons_R ts t x => cons_right (ts :| t) x
    end.

  Lemma view_right_size : forall t t' x, view_right t = cons_right t' x -> tree_size t > tree_size t'.
  Proof.
    intros.
    destruct t ; destruct t' ; simpl in *.
    generalize H ; clear H.
    remember (view_R f) as vf.
    destruct vf ; simpl in * ; intros ; try discriminate.
    symmetry in Heqvf.
    inversion H ; subst.
    assert (eq:=inj_pairT2 H2) ; subst*.
    simpl.
    (*pose (view_R_size_measure f Heqvf). *)
(*     inversion H. *)
(*     simpl. *)
(*     omega. *)
  Admitted.

  (** We wrap concatenation using a simple type but we export the split invariants in an inductive. *)

  Program Definition cat (s s' : FingerTree) : FingerTree :=
    let 's :| ss := s in
    let 'ts' :| ss' := s' in
      _ :| app ss ss'.

  Obligation Tactic := program_simpl.

  Section Splits.

  (**
     The [Split] inductive is is a direct wrapper of the [tree_split] datatype. *)

    Inductive Split (p : v -> bool) (i : v) : Type :=
    mkSplit : forall (l : { l : FingerTree | is_empty l \/
      p (i ∙ tree_measure l) = false }) (x : A) (r : FingerTree | is_empty r \/
      p (i ∙ tree_measure (`l) ∙ measure x) = true), Split p i.

    (** Correspondingly, the function [split] just wraps the original [split_tree] definition. *)

    Program Definition split (p : v -> bool)(i : v) (x : FingerTree | ~ is_empty x)
      : Split p i :=
      let 's :| t := x in
      let (ls, l, x, rs, r) := split_tree p i t in
        mkSplit p i (ls :| ` l) x (rs :| ` r).

  (* end hide *)

    (** %\label{def:split_with}%
       On peut aussi refaire le découpage par rapport à un prédicat sur les [FingerTree].
       On offre la même interface simplement typée qu'en %\Haskell% en définissant la
       fonction [split_with p x]. Cette fonction découpe n'importe quel arbre en regardant
       tout d'abord s'il est vide et sinon en appelant la fonction fortement spécifiée [split]
       avec un accumulateur vide [ε]. On crée alors une paire avec l'arbre à gauche et l'arbre droit
       auquel on ajoute l'élément qui fait changer le prédicat de valeur. On oublie complètement
       les propriétés données par la fonction [split] sur le résultat. *)

    Program Definition split_with (p : v -> bool)
      (x : FingerTree) : FingerTree * FingerTree :=
      if is_empty_dec x then (empty, empty)
      else let (l, x, r) := split p ε x in (l, cons x r).

    (* begin hide *)
    Program Definition takeUntil (p : v -> bool) (x : FingerTree) : FingerTree :=
      fst (split_with p x).

    Program Definition dropUntil (p : v -> bool) (x : FingerTree) : FingerTree :=
      snd (split_with p x).

    Program Definition size_split (x : FingerTree * FingerTree) : nat :=
      let (x,y) := x in tree_size x + tree_size y.

    Require Import Coq.Program.Equality.

(*     Program Definition coerce_tree_split_v (v : Type) (mono : monoid v) (p : v -> bool)  *)
(*       (A : Type) (measure : A -> v) (i : v) (s : v) (t : tree_split mono p measure i s) *)
(*       (s' : v) (H : s = s') : tree_split mono p measure i s' := *)
(*       match t in tree_split _ _ _ _ s return s = s' -> tree_split mono p measure i s' with *)
(*         mkTreeSplit xsm xs x ysm ys => fun H => mkTreeSplit p i xs x ys *)
(*       end H. *)

(*     Lemma cut_tree_split : forall (v : Type) (mono : monoid v) (p : v -> bool)  *)
(*       (A : Type) (measure : A -> v) (i : v) (s : v) *)
(*       (P :  *)
(*         forall xsm, *)
(*           forall {xs : fingertree mono measure xsm | *)
(*             isEmpty xs \/ p (Monoid.mappend mono i xsm) = false}, *)
(*           forall (x : A) (ysm : v), *)
(*             forall {ys : fingertree mono measure ysm | *)
(*               isEmpty ys \/ *)
(*                 p *)
(*                 (Monoid.mappend mono i *)
(*                   (Monoid.mappend mono xsm (measure x))) = true}, *)

(*             tree_split mono p measure i (Monoid.mappend mono xsm (Monoid.mappend mono (measure x) ysm)) ->  *)
(*             Type), *)
(*       forall xsm, *)
(*         forall {xs : fingertree mono measure xsm | *)
(*           isEmpty xs \/ p (Monoid.mappend mono i xsm) = false}, *)
(*         forall (x : A) (ysm : v), *)
(*           forall {ys : fingertree mono measure ysm | *)
(*             isEmpty ys \/ *)
(*             p *)
(*             (Monoid.mappend mono i *)
(*               (Monoid.mappend mono xsm (measure x))) = true}, *)
(*       forall  *)

(*         (b :       forall xsm, *)
(*         forall {xs : fingertree mono measure xsm | *)
(*           isEmpty xs \/ p (Monoid.mappend mono i xsm) = false}, *)
(*         forall (x : A) (ysm : v), *)
(*           forall {ys : fingertree mono measure ysm | *)
(*             isEmpty ys \/ *)
(*             p *)
(*             (Monoid.mappend mono i *)
(*               (Monoid.mappend mono xsm (measure x))) = true}, P xsm xs x ysm ys (mkTreeSplit p i xs x ys)) *)
(*         , *)

(*       forall s' (H : (Monoid.mappend mono xsm (Monoid.mappend mono (measure x) ysm)) = s'), *)

(*             match *)
(*               eq_rect (fun s : v => tree_split mono p measure i s) *)
(*               (mkTreeSplit p i xs x ys) s' H as x0 in (tree_split _ _ _ _ v0) *)
(*                 return P x0 *)
(*               with mkTreeSplit xsm xs x ysm ys =>  *)
(*                 b xsm xs x ysm ys *)
(*             end. *)

    Lemma split_size : forall (p : v -> bool) (t : FingerTree) s,
      split_with p t = s -> tree_size t = size_split s.
    Proof.
      intros.
      induction t.
      unfold split_with.
      unfold split_with in H.
      destruct (is_empty_dec (x :| p0)) ; simpl in * ; auto.
      subst s.
      unfold tree_size, DependentFingerTree.tree_size.
      simpl ; auto.
      assert (He:=isEmpty_ε _ i) ; subst x.
      assert (He:=isEmpty_Empty p0 i).
      subst p0 ; simpl ; auto.
    Admitted.

  End Splits.
  (* end hide *)
End FingerTree.


Require Import Recdef.

From FormalSystems Require Import Base.

Inductive AExp : Type :=
    | AConst : nat -> AExp
    | Var : Loc -> AExp
    | Add : AExp -> AExp -> AExp
    | Sub : AExp -> AExp -> AExp
    | Mul : AExp -> AExp -> AExp
    | Div : AExp -> AExp -> AExp.

Inductive BExp : Type :=
    | BTrue : BExp
    | BFalse : BExp
    | Eq : AExp -> AExp -> BExp
    | Le : AExp -> AExp -> BExp
    | Not : BExp -> BExp
    | And : BExp -> BExp -> BExp
    | Or : BExp -> BExp -> BExp.

Inductive Com : Type :=
    | Skip : Com
    | Asgn : Loc -> AExp -> Com
    | Seq : Com -> Com -> Com
    | If : BExp -> Com -> Com -> Com
    | While : BExp -> Com -> Com.

Definition State : Type := Loc -> nat.

Definition initialState : State := fun _ => 0.

Definition changeState (s : State) (x : Loc) (n : nat) : State :=
  fun y : Loc => if x =? y then n else s y.

Inductive AEval : AExp -> State -> nat -> Prop :=
    | EvalAConst :
        forall (n : nat) (s : State), AEval (AConst n) s n
    | EvalVar :
        forall (v : Loc) (s : State), AEval (Var v) s (s v)
    | EvalAdd :
        forall (a1 a2 : AExp) (s : State) (n1 n2 : nat),
          AEval a1 s n1 -> AEval a2 s n2 -> AEval (Add a1 a2) s (n1 + n2)
    | EvalSub :
        forall (a1 a2 : AExp) (s : State) (n1 n2 : nat),
          AEval a1 s n1 -> AEval a2 s n2 -> AEval (Sub a1 a2) s (n1 - n2)
    | EvalMul :
        forall (a1 a2 : AExp) (s : State) (n1 n2 : nat),
          AEval a1 s n1 -> AEval a2 s n2 -> AEval (Mul a1 a2) s (n1 * n2)
    | EvalDiv :
        forall (a1 a2 : AExp) (s : State) (n1 n2 : nat),
          AEval a1 s n1 -> AEval a2 s n2 -> n2 <> 0 ->
            AEval (Div a1 a2) s (n1 / n2).

#[global] Hint Constructors AEval : core.

Fixpoint aeval (a : AExp) (s : State) : option nat :=
match a with
    | AConst n => Some n
    | Var v => Some (s v)
    | Add a1 a2 => liftM2 plus (aeval a1 s) (aeval a2 s)
    | Sub a1 a2 => liftM2 minus (aeval a1 s) (aeval a2 s)
    | Mul a1 a2 => liftM2 mult (aeval a1 s) (aeval a2 s)
    | Div a1 a2 =>
        match aeval a1 s, aeval a2 s with
            | _, Some 0 => None
            | Some n, Some m => Some (n / m)
            | _, _ => None
        end
end.

Lemma AEval_aeval :
  forall {a : AExp} {s : State} {n : nat},
    AEval a s n -> aeval a s = Some n.
Proof.
  induction 1; cbn; rewrite ?IHAEval1, ?IHAEval2; try reflexivity.
  destruct n2.
    contradiction.
    reflexivity.
Qed.

Lemma aeval_AEval :
  forall {a : AExp} {s : State} {n : nat},
    aeval a s = Some n -> AEval a s n.
Proof.
  induction a; cbn; intros; inv H; auto.
    1-4: destruct (aeval a1 s) eqn: Ha1, (aeval a2 s) eqn: Ha2; inv H1; auto.
      destruct n1.
        inv H0.
        assert (n0 / S n1 = n) by (inv H0; auto). rewrite <- H. auto.
      destruct n0; inv H0.
Qed.

Lemma AEval_det :
  forall {a : AExp} {s : State} {n m : nat},
    AEval a s n -> AEval a s m -> n = m.
Proof.
  intros.
  apply AEval_aeval in H.
  apply AEval_aeval in H0.
  rewrite H0 in H. inv H.
Qed.

Fixpoint loca (a : AExp) : list Loc :=
match a with
    | AConst _ => []
    | Var x => [x]
    | Add a1 a2 => loca a1 ++ loca a2
    | Sub a1 a2 => loca a1 ++ loca a2
    | Mul a1 a2 => loca a1 ++ loca a2
    | Div a1 a2 => loca a1 ++ loca a2
end.

Definition acompatible (a : AExp) (s1 s2 : State) : Prop :=
  forall x : Loc, In x (loca a) -> s1 x = s2 x.

#[global] Hint Resolve in_or_app : core.

Lemma AEval_acompatible :
  forall {a : AExp} {s1 : State} {n : nat},
    AEval a s1 n -> forall {s2 : State},
      acompatible a s1 s2 ->
        AEval a s2 n.
Proof.
  unfold acompatible.
  induction 1; cbn in *; intros; try rewrite H; auto 6.
Qed.

Lemma AEval_acompatible_det :
  forall {a : AExp} {s1 : State} {n1 : nat},
    AEval a s1 n1 ->
    forall {s2 : State} {n2 : nat},
      AEval a s2 n2 ->
      (forall x : Loc, In x (loca a) -> s1 x = s2 x) ->
        n1 = n2.
Proof.
  induction 1; cbn; intros;
  match goal with
      | H : AEval ?a _ _ |- _ => is_var a + inv H
  end; eauto 10.
Qed.

Inductive BEval : BExp -> State -> bool -> Prop :=
    | EvalTrue :
        forall s : State, BEval BTrue s true
    | EvalFalse :
        forall s : State, BEval BFalse s false
    | EvalEq :
        forall (a1 a2 : AExp) (s : State) (n m : nat),
          AEval a1 s n -> AEval a2 s m -> BEval (Eq a1 a2) s (Nat.eqb n m)
    | EvalLe :
        forall (a1 a2 : AExp) (s : State) (n m : nat),
          AEval a1 s n -> AEval a2 s m -> BEval (Le a1 a2) s (Nat.leb n m)
    | EvalNot :
        forall (e : BExp) (s : State) (b : bool),
          BEval e s b -> BEval (Not e) s (negb b)
    | EvalAnd :
        forall (e1 e2 : BExp) (s : State) (b1 b2 : bool),
          BEval e1 s b1 -> BEval e2 s b2 -> BEval (And e1 e2) s (andb b1 b2)
    | EvalOr :
        forall (e1 e2 : BExp) (s : State) (b1 b2 : bool),
          BEval e1 s b1 -> BEval e2 s b2 -> BEval (Or e1 e2) s (orb b1 b2).

#[global] Hint Constructors BEval : core.

Fixpoint beval (e : BExp) (s : State) : option bool :=
match e with
    | BTrue => Some true
    | BFalse => Some false
    | Eq a1 a2 => liftM2 Nat.eqb (aeval a1 s) (aeval a2 s)
    | Le a1 a2 => liftM2 Nat.leb (aeval a1 s) (aeval a2 s)
    | Not e' => omap negb (beval e' s)
    | And e1 e2 => liftM2 andb (beval e1 s) (beval e2 s)
    | Or e1 e2 => liftM2 orb (beval e1 s) (beval e2 s)
end.

Lemma BEval_beval :
  forall {e : BExp} {s : State} {b : bool},
    BEval e s b -> beval e s = Some b.
Proof.
  induction 1; cbn.
    1-2: reflexivity.
    1-2: rewrite (AEval_aeval H), (AEval_aeval H0); reflexivity.
    rewrite IHBEval. reflexivity.
    1-2: rewrite IHBEval1, IHBEval2; reflexivity.
Qed.

#[global] Hint Resolve aeval_AEval : core.

Lemma beval_BEval :
  forall {e : BExp} {s : State} {b : bool},
    beval e s = Some b -> BEval e s b.
Proof.
  induction e; cbn; intros; inv H; auto.
    destruct (aeval a s) eqn: Ha1, (aeval a0 s) eqn: Ha2; inv H1; auto.
    destruct (aeval a s) eqn: Ha1, (aeval a0 s) eqn: Ha2; inv H1; auto.
    destruct (beval e s) eqn: He; inv H1; auto.
    destruct (beval e1 s) eqn: He1, (beval e2 s) eqn: He2; inv H1; auto.
    destruct (beval e1 s) eqn: He1, (beval e2 s) eqn: He2; inv H1; auto.
Qed.

Lemma BEval_det :
  forall {e : BExp} {s : State} {b1 : bool},
    BEval e s b1 -> forall {b2 : bool}, BEval e s b2 -> b1 = b2.
Proof.
  intros.
  apply BEval_beval in H.
  apply BEval_beval in H0.
  rewrite H0 in H. inv H.
Qed.

Fixpoint locb (b : BExp) : list Loc :=
match b with
    | BTrue => []
    | BFalse => []
    | Eq a1 a2 => loca a1 ++ loca a2
    | Le a1 a2 => loca a1 ++ loca a2
    | Not b' => locb b'
    | And b1 b2 => locb b1 ++ locb b2
    | Or b1 b2 => locb b1 ++ locb b2
end.

Definition bcompatible (b : BExp) (s1 s2 : State) : Prop :=
  forall x : Loc, In x (locb b) -> s1 x = s2 x.

#[global] Hint Resolve AEval_acompatible : core.
#[global] Hint Unfold acompatible : core.

Lemma BEval_bcompatible :
  forall {e : BExp} {s1 : State} {b : bool},
    BEval e s1 b -> forall {s2 : State},
      bcompatible e s1 s2 -> BEval e s2 b.
Proof.
  unfold bcompatible.
  induction 1; cbn in *; intros; constructor; eauto 6.
Qed.

Lemma BEval_bcompatible_det :
  forall {e : BExp} {s1 : State} {b1 : bool},
    BEval e s1 b1 -> forall {s2 : State} {b2 : bool},
    BEval e s2 b2 ->
      bcompatible e s1 s2 -> b1 = b2.
Proof.
  intros.
  assert (BEval e s2 b1).
    eapply BEval_bcompatible; eauto.
  eapply BEval_det; eauto.
Qed.

Inductive CEval : Com -> State -> State -> Prop :=
    | EvalSkip :
        forall s : State, CEval Skip s s
    | EvalAsgn :
        forall (v : Loc) (a : AExp) (s : State) (n : nat),
          AEval a s n -> CEval (Asgn v a) s (changeState s v n)
    | EvalSeq :
        forall (c1 c2 : Com) (s1 s2 s3 : State),
          CEval c1 s1 s2 -> CEval c2 s2 s3 -> CEval (Seq c1 c2) s1 s3
    | EvalIfFalse :
        forall (b : BExp) (c1 c2 : Com) (s1 s2 : State),
          BEval b s1 false -> CEval c2 s1 s2 -> CEval (If b c1 c2) s1 s2
    | EvalIfTrue :
        forall (b : BExp) (c1 c2 : Com) (s1 s2 : State),
          BEval b s1 true -> CEval c1 s1 s2 -> CEval (If b c1 c2) s1 s2
    | EvalWhileFalse :
        forall (b : BExp) (c : Com) (s : State),
          BEval b s false -> CEval (While b c) s s
    | EvalWhileTrue :
        forall (b : BExp) (c : Com) (s1 s2 s3 : State),
          BEval b s1 true ->
          CEval c s1 s2 -> CEval (While b c) s2 s3 ->
            CEval (While b c) s1 s3.

#[global] Hint Constructors CEval : core.

#[global] Hint Rewrite @AEval_det : core.
#[global] Hint Resolve AEval_det BEval_det : core.

Lemma CEval_det :
  forall (c : Com) (s s1 : State),
    CEval c s s1 -> forall s2 : State, CEval c s s2 -> s1 = s2.
Proof.
  induction 1; intros.
  Ltac wut :=
  match goal with
      | H : CEval ?c _ _ |- _ => is_var c + inv H
  end;
  repeat match goal with
      | IH : forall _, CEval _ _ _ -> _, H : CEval _ _ _ |- _ =>
          let H' := fresh "H" in
            assert (H' := IH _ H); clear H; rename H' into H; subst
      | H : BEval ?b ?s _, H' : BEval ?b ?s _ |- _ =>
          let H'' := fresh "H" in
            assert (H'' := BEval_det H H'); clear H H'
  end; eauto; try congruence.
  all: wut.
Qed.

Function ceval (n : nat) (c : Com) (s : State) : option State :=
match n with
    | 0 => None
    | S n' =>
        match c with
            | Skip => Some s
            | Asgn x a => omap (changeState s x) (aeval a s)
            | Seq c1 c2 =>
                match ceval n' c1 s with
                    | None => None
                    | Some s' => ceval n' c2 s'
                end
            | If b c1 c2 =>
                match beval b s with
                    | None => None
                    | Some true => ceval n' c1 s
                    | Some false => ceval n' c2 s
                end
            | While b c =>
                match beval b s with
                    | None => None
                    | Some true =>
                        match ceval n' c s with
                            | None => None
                            | Some s' => ceval n' (While b c) s'
                        end
                    | Some false => Some s
                end
        end
end.

#[global] Hint Immediate aeval_AEval beval_BEval : core.

Lemma ceval_CEval :
  forall (n : nat) (c : Com) (s1 s2 : State),
    ceval n c s1 = Some s2 -> CEval c s1 s2.
Proof.
  intros n c s1.
  functional induction ceval n c s1; intros; inv H; eauto.
  destruct (aeval a s) eqn: Ha; inv H1; auto.
Qed.

Lemma while_true_do_skip :
  forall s1 s2 : State,
    ~ CEval (While BTrue Skip) s1 s2.
Proof.
  intros s1 s2 H.
  remember (While BTrue Skip) as w. revert Heqw.
  induction H; intros; inv Heqw. inv H.
Qed.

Lemma div_0 :
  forall (a1 a2 : AExp) (s : State) (n2 : nat),
    AEval a2 s 0 -> forall m : nat, ~ AEval (Div a1 a2) s m.
Proof.
  intros; intro. inv H0.
Qed.