header {*\isaheader{Implementing Unique Priority Queues by Annotated Lists}*}
theory PrioUniqueByAnnotatedList
imports
  "../spec/AnnotatedListSpec"
  "../spec/PrioUniqueSpec"
begin

text {*
  In this theory we use annotated lists to implement unique priority queues
  with totally ordered elements.

  This theory is written as a generic adapter from the AnnotatedList interface
  to the unique priority queue interface.

  The annotated list stores a sequence of elements annotated with
  priorities\footnote{Technically, the annotated list elements are of unit-type,
  and the annotations hold both, the priority queue elements and the priorities.
  This is required as we defined annotated lists to only sum up the elements
  annotations.}

  The monoids operations forms the maximum over the elements and
  the minimum over the priorities.
  The sequence of pairs is ordered by ascending elements' order.
  The insertion point for a new element, or the priority of an existing element
  can be found by splitting the
  sequence at the point where the maximum of the elements read so far gets
  bigger than the element to be inserted.

  The minimum priority can be read out as the sum over the whole sequence.
  Finding the element with minimum priority is done by splitting the sequence
  at the point where the minimum priority of the elements read so far becomes
  equal to the minimum priority of the whole sequence.
*}

subsection "Definitions"

subsubsection "Monoid"
datatype ('e, 'a) LP = Infty | LP 'e 'a

fun p_unwrap :: "('e,'a) LP \<Rightarrow> ('e \<times> 'a)" where
  "p_unwrap (LP e a) = (e , a)"

fun p_min :: "('e::linorder, 'a::linorder) LP \<Rightarrow> ('e, 'a) LP \<Rightarrow> ('e, 'a) LP"  where
  "p_min Infty Infty = Infty"|
  "p_min Infty (LP e a) = LP e a"|
  "p_min (LP e a) Infty = LP e a"|
  "p_min (LP e1 a) (LP e2 b) = (LP (max e1 e2) (min a b))"

fun e_less_eq :: "'e \<Rightarrow> ('e::linorder, 'a::linorder) LP \<Rightarrow> bool"  where
  "e_less_eq e Infty = False"|
  "e_less_eq e (LP e' _) = (e \<le> e')"

text_raw{*\paragraph{Instantiation of classes}\ \\*}
lemma p_min_re_neut[simp]: "p_min a Infty = a" by (induct a) auto
lemma p_min_le_neut[simp]: "p_min Infty a = a" by (induct a) auto
lemma p_min_asso: "p_min (p_min a b) c = p_min a (p_min b c)"
  apply(induct a b  rule: p_min.induct )
  apply (auto)
  apply (induct c)
  apply (auto)
apply (metis max.assoc)
apply (metis min.assoc)
  done

lemma lp_mono: "class.monoid_add p_min Infty" by  unfold_locales  (auto simp add: p_min_asso)

instantiation LP :: (linorder,linorder) monoid_add
begin
definition zero_def: "0 == Infty"
definition plus_def: "a+b == p_min a b"

instance by
  intro_classes
(auto simp add: p_min_asso zero_def plus_def)
end

fun p_less_eq :: "('e, 'a::linorder) LP \<Rightarrow> ('e, 'a) LP \<Rightarrow> bool" where
  "p_less_eq (LP e a) (LP f b) = (a \<le> b)"|
  "p_less_eq  _ Infty = True"|
  "p_less_eq Infty (LP e a) = False"

fun p_less :: "('e, 'a::linorder) LP \<Rightarrow> ('e, 'a) LP \<Rightarrow> bool" where
  "p_less (LP e a) (LP f b) = (a < b)"|
  "p_less (LP e a) Infty = True"|
  "p_less Infty _ = False"

lemma p_less_le_not_le : "p_less x y \<longleftrightarrow> p_less_eq x y \<and> \<not> (p_less_eq y x)"
  by (induct x y rule: p_less.induct) auto

lemma p_order_refl : "p_less_eq x x"
  by (induct x) auto

lemma p_le_inf : "p_less_eq Infty x \<Longrightarrow> x = Infty"
  by (induct x) auto

lemma p_order_trans : "\<lbrakk>p_less_eq x y; p_less_eq y z\<rbrakk> \<Longrightarrow> p_less_eq x z"
  apply (induct y z rule: p_less.induct)
  apply auto
  apply (induct x)
  apply auto
  apply (cases x)
  apply auto
  apply(induct x)
  apply (auto simp add: p_le_inf)
  apply (metis p_le_inf p_less_eq.simps(2))
  done

lemma p_linear2 : "p_less_eq x y \<or> p_less_eq y x"
  apply (induct x y rule: p_less_eq.induct)
  apply auto
  done

instantiation LP :: (type, linorder) preorder
begin
definition plesseq_def: "less_eq = p_less_eq"
definition pless_def: "less = p_less"

instance
  apply (intro_classes)
  apply (simp only: p_less_le_not_le pless_def plesseq_def)
  apply (simp only: p_order_refl plesseq_def pless_def)
  apply (simp only: plesseq_def)
  apply (metis p_order_trans)
  done

end

subsubsection "Operations"

definition aluprio_\<alpha> :: "('s \<Rightarrow> (unit \<times> ('e::linorder,'a::linorder) LP) list)
  \<Rightarrow> 's \<Rightarrow> ('e::linorder \<rightharpoonup>  'a::linorder)"
  where
  "aluprio_\<alpha> \<alpha> ft == (map_of (map p_unwrap (map snd (\<alpha> ft))))"

definition aluprio_invar :: "('s \<Rightarrow> (unit \<times> ('c::linorder, 'd::linorder) LP) list)
  \<Rightarrow> ('s \<Rightarrow> bool) \<Rightarrow> 's \<Rightarrow> bool"
  where
  "aluprio_invar \<alpha> invar ft ==
     invar ft
     \<and> (\<forall> x\<in>set (\<alpha> ft). snd x\<noteq>Infty)
     \<and> sorted (map fst (map p_unwrap (map snd (\<alpha> ft))))
     \<and> distinct (map fst (map p_unwrap (map snd (\<alpha> ft)))) "

definition aluprio_empty  where
  "aluprio_empty empt = empt"

definition aluprio_isEmpty  where
  "aluprio_isEmpty isEmpty = isEmpty"

definition aluprio_insert ::
  "((('e::linorder,'a::linorder) LP \<Rightarrow> bool)
  \<Rightarrow> ('e,'a) LP \<Rightarrow> 's \<Rightarrow> ('s \<times> (unit \<times> ('e,'a) LP) \<times> 's))
    \<Rightarrow> ('s \<Rightarrow> ('e,'a) LP)
      \<Rightarrow> ('s \<Rightarrow> bool)
        \<Rightarrow> ('s \<Rightarrow> 's \<Rightarrow> 's)
          \<Rightarrow> ('s \<Rightarrow> unit \<Rightarrow> ('e,'a) LP \<Rightarrow> 's)
            \<Rightarrow> 's \<Rightarrow> 'e \<Rightarrow> 'a \<Rightarrow> 's"
  where
  "
  aluprio_insert splits annot isEmpty app consr s e a =
    (if e_less_eq e (annot s) \<and> \<not> isEmpty s
    then
      (let (l, (_,lp) , r) = splits (e_less_eq e) Infty s in
        (if e < fst (p_unwrap lp)
        then
          app (consr (consr l () (LP e a))  () lp) r
        else
          app (consr l () (LP e a)) r  ))
    else
      consr s () (LP e a))
  "

definition aluprio_pop :: "((('e::linorder,'a::linorder) LP \<Rightarrow> bool) \<Rightarrow> ('e,'a) LP
  \<Rightarrow> 's \<Rightarrow> ('s \<times> (unit \<times> ('e,'a) LP) \<times> 's))
    \<Rightarrow> ('s \<Rightarrow> ('e,'a) LP)
      \<Rightarrow> ('s \<Rightarrow> 's \<Rightarrow> 's)
        \<Rightarrow> 's
          \<Rightarrow> 'e \<times>'a \<times>'s"
  where
  "aluprio_pop splits annot app s =
    (let (l, (_,lp) , r) = splits (\<lambda> x. x \<le> (annot s)) Infty s
    in
      (case lp of
        (LP e a) \<Rightarrow>
          (e, a, app l r) ))"

definition aluprio_prio ::
  "((('e::linorder,'a::linorder) LP \<Rightarrow> bool) \<Rightarrow> ('e,'a) LP \<Rightarrow> 's
  \<Rightarrow> ('s \<times> (unit \<times> ('e,'a) LP) \<times> 's))
    \<Rightarrow> ('s \<Rightarrow> ('e,'a) LP)
      \<Rightarrow> ('s \<Rightarrow> bool)
        \<Rightarrow> 's \<Rightarrow> 'e \<Rightarrow> 'a option"
  where
  "
  aluprio_prio splits annot isEmpty s e =
    (if e_less_eq e (annot s) \<and> \<not> isEmpty s
    then
      (let (l, (_,lp) , r) = splits (e_less_eq e) Infty s in
        (if e = fst (p_unwrap lp)
        then
          Some (snd (p_unwrap lp))
        else
          None))
    else
      None)
  "

lemmas aluprio_defs =
aluprio_invar_def
aluprio_\<alpha>_def
aluprio_empty_def
aluprio_isEmpty_def
aluprio_insert_def
aluprio_pop_def
aluprio_prio_def

subsection "Correctness"

subsubsection "Auxiliary Lemmas"

lemma p_linear: "(x::('e, 'a::linorder) LP) \<le> y \<or> y \<le> x"
  by (unfold plesseq_def) (simp only: p_linear2)

lemma e_less_eq_mon1: "e_less_eq e x \<Longrightarrow> e_less_eq e (x + y)"
  apply (cases x)
  apply (auto simp add: plus_def)
  apply (cases y)
  apply (auto simp add: max.coboundedI1)
  done
lemma e_less_eq_mon2: "e_less_eq e y \<Longrightarrow> e_less_eq e (x + y)"
  apply (cases x)
  apply (auto simp add: plus_def)
  apply (cases y)
  apply (auto simp add: max.coboundedI2)
  done
lemmas e_less_eq_mon =
  e_less_eq_mon1
  e_less_eq_mon2

lemma p_less_eq_mon:
  "(x::('e::linorder,'a::linorder) LP) \<le> z \<Longrightarrow> (x + y) \<le> z"
  apply(cases y)
  apply(auto simp add: plus_def)
  apply (cases x)
  apply (cases z)
  apply (auto simp add: plesseq_def)
  apply (cases z)
  apply (auto simp add: min.coboundedI1)
  done

lemma e_less_eq_listsum:
  "\<lbrakk>\<not> e_less_eq e (listsum xs)\<rbrakk> \<Longrightarrow> \<forall>x \<in> set xs. \<not> e_less_eq e x"
proof (induct xs)
  case Nil thus ?case by simp
next
  case (Cons a xs)
  hence "\<not> e_less_eq e (listsum xs)" by (auto simp add: e_less_eq_mon)
  hence v1: "\<forall>x\<in>set xs. \<not> e_less_eq e x" using Cons.hyps by simp
  from Cons.prems have "\<not> e_less_eq e a" by (auto simp add: e_less_eq_mon)
  with v1 show "\<forall>x\<in>set (a#xs). \<not> e_less_eq e x" by simp
qed

lemma e_less_eq_p_unwrap:
  "\<lbrakk>x \<noteq> Infty;\<not> e_less_eq e x\<rbrakk> \<Longrightarrow> fst (p_unwrap x) < e"
  by (cases x) auto

lemma e_less_eq_refl :
  "b \<noteq> Infty \<Longrightarrow> e_less_eq (fst (p_unwrap b)) b"
  by (cases b) auto

lemma e_less_eq_listsum2:
  assumes
  "\<forall>x\<in>set (\<alpha>s). snd x \<noteq> Infty"
  "((), b) \<in> set (\<alpha>s)"
  shows "e_less_eq (fst (p_unwrap b)) (listsum (map snd (\<alpha>s)))"
  apply(insert assms)
  apply (induct "\<alpha>s")
  apply (auto simp add: zero_def e_less_eq_mon e_less_eq_refl)
  done

lemma e_less_eq_lem1:
  "\<lbrakk>\<not> e_less_eq e a;e_less_eq e (a + b)\<rbrakk> \<Longrightarrow> e_less_eq e b"
  apply (auto simp add: plus_def)
  apply (cases a)
  apply auto
  apply (cases b)
  apply auto
  apply (metis le_max_iff_disj)
  done

lemma p_unwrap_less_sum: "snd (p_unwrap ((LP e aa) + b)) \<le> aa"
  apply (cases b)
  apply (auto simp add: plus_def)
done

lemma  listsum_less_elems: "\<forall>x\<in>set xs. snd x \<noteq> Infty \<Longrightarrow>
  \<forall>y\<in>set (map snd (map p_unwrap (map snd xs))).
              snd (p_unwrap (listsum (map snd xs))) \<le> y"
    proof (induct xs)
    case Nil thus ?case by simp
    next
    case (Cons a as) thus ?case
      apply auto
      apply (cases "(snd a)" rule: p_unwrap.cases)
      apply auto
      apply (cases "listsum (map snd as)")
      apply auto
      apply (metis linorder_linear p_min_re_neut p_unwrap.simps
        plus_def[abs_def] snd_eqD)
      apply (auto simp add: p_unwrap_less_sum)
      apply (unfold plus_def)
      apply (cases "(snd a, listsum (map snd as))" rule: p_min.cases)
      apply auto
      apply (cases "map snd as")
      apply (auto simp add: infadd)
      apply (metis min.coboundedI2 snd_conv)
      done
qed

lemma distinct_sortet_list_app:
  "\<lbrakk>sorted xs; distinct xs; xs = as @ b # cs\<rbrakk>
  \<Longrightarrow> \<forall> x\<in> set cs. b < x"
  by (metis distinct.simps(2) distinct_append
    linorder_antisym_conv2 sorted_Cons sorted_append)

lemma distinct_sorted_list_lem1:
  assumes
  "sorted xs"
  "sorted ys"
  "distinct xs"
  "distinct ys"
  " \<forall> x \<in> set xs. x < e"
  " \<forall> y \<in> set ys. e < y"
  shows
  "sorted (xs @ e # ys)"
  "distinct (xs @ e # ys)"
proof -
  from assms (5,6)
  have "\<forall>x\<in>set xs. \<forall>y\<in>set ys. x \<le> y" by force
  thus "sorted (xs @ e # ys)"
    using assms
    by (auto simp add: sorted_append sorted_Cons)
  have "set xs \<inter> set ys = {}" using assms (5,6) by force
  thus "distinct (xs @ e # ys)"
    using assms
    by (auto simp add: distinct_append)
qed

lemma distinct_sorted_list_lem2:
  assumes
  "sorted xs"
  "sorted ys"
  "distinct xs"
  "distinct ys"
  "e < e'"
  " \<forall> x \<in> set xs. x < e"
  " \<forall> y \<in> set ys. e' < y"
  shows
  "sorted (xs @ e # e' # ys)"
  "distinct (xs @ e # e' # ys)"
proof -
  have "sorted (e' # ys)"
    "distinct (e' # ys)"
    "\<forall> y \<in> set (e' # ys). e < y"
    using assms(2,4,5,7)
    by (auto simp add: sorted_Cons)
  thus "sorted (xs @ e # e' # ys)"
  "distinct (xs @ e # e' # ys)"
    using assms(1,3,6) distinct_sorted_list_lem1[of xs "e' # ys" e]
    by auto
qed

lemma map_of_distinct_upd:
  "x \<notin> set (map fst xs) \<Longrightarrow> [x \<mapsto> y] ++ map_of xs = (map_of xs) (x \<mapsto> y)"
  by (induct xs) (auto simp add: fun_upd_twist)

lemma map_of_distinct_upd2:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ (x,y) # ys) = (map_of (xs @ ys))(x \<mapsto> y)"
  apply(insert assms)
  apply(induct xs)
  apply (auto intro: ext)
  done

lemma map_of_distinct_upd3:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ (x,y) # ys) = (map_of (xs @ (x,y') # ys))(x \<mapsto> y)"
  apply(insert assms)
  apply(induct xs)
  apply (auto intro: ext)
  done

lemma map_of_distinct_upd4:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ ys) = (map_of (xs @ (x,y) # ys))(x := None)"
  apply(insert assms)
  apply(induct xs)

  apply clarsimp
  apply (metis dom_map_of_conv_image_fst fun_upd_None_restrict
    restrict_complement_singleton_eq restrict_map_self)

  apply (auto simp add: map_of_eq_None_iff) []
  done

lemma map_of_distinct_lookup:
  assumes "x \<notin> set(map fst xs)"
  "x \<notin> set (map fst ys)"
  shows "map_of (xs @ (x,y) # ys) x = Some y"
proof -
  have "map_of (xs @ (x,y) # ys) = (map_of (xs @ ys)) (x \<mapsto> y)"
    using assms map_of_distinct_upd2 by simp
  thus ?thesis
    by simp
qed

lemma ran_distinct:
  assumes dist: "distinct (map fst al)"
  shows "ran (map_of al) = snd ` set al"
using assms proof (induct al)
  case Nil then show ?case by simp
next
  case (Cons kv al)
  then have "ran (map_of al) = snd ` set al" by simp
  moreover from Cons.prems have "map_of al (fst kv) = None"
    by (simp add: map_of_eq_None_iff)
  ultimately show ?case by (simp only: map_of.simps ran_map_upd) simp
qed

subsubsection "Finite"

lemma aluprio_finite_correct: "uprio_finite (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar)"
  by(unfold_locales) (simp add: aluprio_defs finite_dom_map_of)

subsubsection "Empty"
lemma aluprio_empty_correct:
  assumes "al_empty \<alpha> invar empt"
  shows "uprio_empty (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_empty empt)"
proof -
  interpret al_empty \<alpha> invar empt by fact
  show ?thesis
    apply (unfold_locales)
    apply (auto simp add: empty_correct aluprio_defs)
    done
qed

subsubsection "Is Empty"

lemma aluprio_isEmpty_correct:
  assumes "al_isEmpty \<alpha> invar isEmpty"
  shows "uprio_isEmpty (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_isEmpty isEmpty)"
proof -
  interpret al_isEmpty \<alpha> invar isEmpty by fact
  show ?thesis
    apply (unfold_locales)
    apply (auto simp add: aluprio_defs isEmpty_correct)
    done
qed

subsubsection "Insert"

lemma annot_inf:
  assumes A: "invar s" "\<forall>x\<in>set (\<alpha> s). snd x \<noteq> Infty" "al_annot \<alpha> invar annot"
  shows "annot s = Infty \<longleftrightarrow> \<alpha> s = [] "
proof -
  from A have invs: "invar s" by (simp add: aluprio_defs)
  interpret al_annot \<alpha> invar annot by fact
  show "annot s = Infty \<longleftrightarrow> \<alpha> s = []"
  proof (cases "\<alpha> s = []")
    case True
    hence "map snd (\<alpha> s) = []" by simp
    hence "listsum (map snd (\<alpha> s)) = Infty"
      by (auto simp add: zero_def)
    with invs have  "annot s = Infty" by (auto simp add: annot_correct)
    with True show ?thesis by simp
  next
    case False
    hence " \<exists>x xs. (\<alpha> s) = x # xs" by (cases "\<alpha> s") auto
    from this obtain x xs where [simp]: "(\<alpha> s) = x # xs" by blast
    from this assms(2) have "snd x \<noteq> Infty" by (auto simp add: aluprio_defs)
    hence "listsum (map snd (\<alpha> s)) \<noteq> Infty" by (auto simp add: infadd)
    thus ?thesis using annot_correct invs False by simp
  qed
qed

lemma e_less_eq_annot:

  assumes "al_annot \<alpha> invar annot"
   "invar s" "\<forall>x\<in>set (\<alpha> s). snd x \<noteq> Infty" "\<not> e_less_eq e (annot s)"
  shows "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s)). x < e"
proof -
  interpret al_annot \<alpha> invar annot by fact
  from assms(2) have "annot s = listsum (map snd (\<alpha> s))"
    by (auto simp add: annot_correct)
  with assms(4) have
    "\<forall>x \<in> set (map snd (\<alpha> s)). \<not> e_less_eq e x"
    by (metis e_less_eq_listsum)
  with assms(3)
  show ?thesis
    by (auto simp add: e_less_eq_p_unwrap)
qed

lemma aluprio_insert_correct:
  assumes
  "al_splits \<alpha> invar splits"
  "al_annot \<alpha> invar annot"
  "al_isEmpty \<alpha> invar isEmpty"
  "al_app \<alpha> invar app"
  "al_consr \<alpha> invar consr"
  shows
  "uprio_insert (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar)
    (aluprio_insert splits annot isEmpty app consr)"
proof -
  interpret al_splits \<alpha> invar splits by fact
  interpret al_annot \<alpha> invar annot by fact
  interpret al_isEmpty \<alpha> invar isEmpty by fact
  interpret al_app \<alpha> invar app by fact
  interpret al_consr \<alpha> invar consr by fact
  show ?thesis
  proof (unfold_locales,unfold aluprio_defs)
    case goal1 note g1asms = this
    thus ?case proof (cases "e_less_eq e (annot s) \<and> \<not> isEmpty s")
      case False with g1asms show  ?thesis
        apply (auto simp add: consr_correct )
      proof -
        case goal1
        with assms(2) have
          "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s)). x < e"
          by (simp add: e_less_eq_annot)
        with goal1(3) show ?case
          by(auto simp add: sorted_append)
      next
        case goal2
        hence "annot s = listsum (map snd (\<alpha> s))"
          by (simp add: annot_correct)
        with goal2
        show ?case
          by (auto simp add: e_less_eq_listsum2)
      next
        case goal3
        hence "\<alpha> s = []" by (auto simp add: isEmpty_correct)
        thus ?case by simp
      next
        case goal4
        hence "\<alpha> s = []" by (auto simp add: isEmpty_correct)
        with goal4 show ?case by simp
      qed
    next
      case True note T1 = this
      obtain l uu lp r where
        l_lp_r: "(splits (e_less_eq e) Infty s) = (l, ((), lp), r) "
        by (cases "splits (e_less_eq e) Infty s", auto)
      note v2 = splits_correct[of s "e_less_eq e" Infty l "()" lp r]
      have
        v3: "invar s"
        "\<not> e_less_eq e Infty"
        "e_less_eq e (Infty + listsum (map snd (\<alpha> s)))"
        using T1 g1asms annot_correct
        by (auto simp add: plus_def)
      have
        v4: "\<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
        "\<not> e_less_eq e (Infty + listsum (map snd (\<alpha> l)))"
        "e_less_eq e (Infty + listsum (map snd (\<alpha> l)) + lp)"
        "invar l"
        "invar r"
        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto
      hence v5: "e_less_eq e lp"
        by (metis e_less_eq_lem1)
      hence v6: "e \<le> (fst (p_unwrap lp))"
        by (cases lp) auto
      have "(Infty + listsum (map snd (\<alpha> l))) = (annot l)"
        by (metis add_0_left annot_correct v4(4) zero_def)
      hence v7:"\<not> e_less_eq e (annot l)"
        using v4(2) by simp
      have "\<forall>x\<in>set (\<alpha> l). snd x \<noteq> Infty"
        using g1asms v4(1) by simp
      hence v7: "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> l)). x < e"
        using v4(4) v7 assms(2)
        by(simp add: e_less_eq_annot)
      have v8:"map fst (map p_unwrap (map snd (\<alpha> s))) =
        map fst (map p_unwrap (map snd (\<alpha> l))) @ fst(p_unwrap lp) #
        map fst (map p_unwrap (map snd (\<alpha> r)))"
        using v4(1)
        by simp
      note distinct_sortet_list_app[of "map fst (map p_unwrap (map snd (\<alpha> s)))"
        "map fst (map p_unwrap (map snd (\<alpha> l)))" "fst(p_unwrap lp)"
        "map fst (map p_unwrap (map snd (\<alpha> r)))"]
      hence v9:
        "\<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). fst(p_unwrap lp) < x"
        using v4(1) g1asms v8
        by auto
      have v10:
        "sorted (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "distinct (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "sorted (map fst (map p_unwrap (map snd (\<alpha> r))))"
        "distinct (map fst (map p_unwrap (map snd (\<alpha> l))))"
        using g1asms v8
        by (auto simp add: sorted_append sorted_Cons)

      from l_lp_r T1 g1asms show ?thesis
      proof (fold aluprio_insert_def, cases "e < fst (p_unwrap lp)")
        case True
        hence v11:
          "aluprio_insert splits annot isEmpty app consr s e a
            = app (consr (consr l () (LP e a)) () lp) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have  v12: "invar (app (consr (consr l () (LP e a)) () lp) r)"
          using v4(4,5)
          by (auto simp add: app_correct consr_correct)
        have v13:
          "\<alpha> (app (consr (consr l () (LP e a)) () lp) r)
            = \<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        hence v14:
          "(\<forall>x\<in>set (\<alpha> (app (consr (consr l () (LP e a)) () lp) r)).
             snd x \<noteq> Infty)"
          using g1asms v4(1)
          by auto
        have v15: "e = fst(p_unwrap (LP e a))" by simp
        hence v16:
          "sorted (map fst (map p_unwrap
             (map snd (\<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r))))"
          "distinct (map fst (map p_unwrap
             (map snd (\<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r))))"
          using v10(1,3) v7 True v9 v4(1) g1asms distinct_sorted_list_lem2
          by (auto simp add: sorted_append sorted_Cons)
        thus "invar (aluprio_insert splits annot isEmpty app consr s e a) \<and>
          (\<forall>x\<in>set (\<alpha> (aluprio_insert splits annot isEmpty app consr s e a)).
             snd x \<noteq> Infty) \<and>
          sorted (map fst (map p_unwrap (map snd (\<alpha>
             (aluprio_insert splits annot isEmpty app consr s e a))))) \<and>
          distinct (map fst (map p_unwrap (map snd (\<alpha>
             (aluprio_insert splits annot isEmpty app consr s e a)))))"
          using v11 v12 v13 v14
          by simp
      next
        case False
        hence v11:
          "aluprio_insert splits annot isEmpty app consr s e a
             = app (consr l () (LP e a)) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have  v12: "invar (app (consr l () (LP e a)) r)" using v4(4,5)
          by (auto simp add: app_correct consr_correct)
        have v13: "\<alpha> (app (consr l () (LP e a)) r) = \<alpha> l @ ((),(LP e a)) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        hence v14: "(\<forall>x\<in>set (\<alpha> (app (consr l () (LP e a)) r)). snd x \<noteq> Infty)"
          using g1asms v4(1)
          by auto
        have v15: "e = fst(p_unwrap (LP e a))" by simp
        have v16: "e = fst(p_unwrap lp)"
          using False v5 by (cases lp) auto
        hence v17:
          "sorted (map fst (map p_unwrap
            (map snd (\<alpha> l @ ((),(LP e a)) # \<alpha> r))))"
          "distinct (map fst (map p_unwrap
            (map snd (\<alpha> l @ ((),(LP e a)) # \<alpha> r))))"
          using v16 v15 v10(1,3) v7 True v9 v4(1)
            g1asms distinct_sorted_list_lem1
          by (auto simp add: sorted_append sorted_Cons)
        thus "invar (aluprio_insert splits annot isEmpty app consr s e a) \<and>
          (\<forall>x\<in>set (\<alpha> (aluprio_insert splits annot isEmpty app consr s e a)).
            snd x \<noteq> Infty) \<and>
          sorted (map fst (map p_unwrap (map snd (\<alpha>
            (aluprio_insert splits annot isEmpty app consr s e a))))) \<and>
          distinct (map fst (map p_unwrap (map snd (\<alpha>
            (aluprio_insert splits annot isEmpty app consr s e a)))))"
          using v11 v12 v13 v14
          by simp
      qed
    qed
  next
    case goal2 note g1asms = this
    thus ?case proof (cases "e_less_eq e (annot s) \<and> \<not> isEmpty s")
      case False with g1asms show  ?thesis
        apply (auto simp add: consr_correct)
      proof -
        case goal1
        with assms(2) have
          "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s)). x < e"
          by (simp add: e_less_eq_annot)
        hence "e \<notin> set (map fst ((map (p_unwrap \<circ> snd)) (\<alpha> s)))"
          by auto
        thus ?case
          by (auto simp add: map_of_distinct_upd)
      next
        case goal2
        hence "\<alpha> s = []" by (auto simp add: isEmpty_correct)
        thus ?case
          by simp
      qed
    next
      case True note T1 = this
      obtain l uu lp r where
        l_lp_r: "(splits (e_less_eq e) Infty s) = (l, ((), lp), r) "
        by (cases "splits (e_less_eq e) Infty s", auto)
      note v2 = splits_correct[of s "e_less_eq e" Infty l "()" lp r]
      have
        v3: "invar s"
        "\<not> e_less_eq e Infty"
        "e_less_eq e (Infty + listsum (map snd (\<alpha> s)))"
        using T1 g1asms annot_correct
        by (auto simp add: plus_def)
      have
        v4: "\<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
        "\<not> e_less_eq e (Infty + listsum (map snd (\<alpha> l)))"
        "e_less_eq e (Infty + listsum (map snd (\<alpha> l)) + lp)"
        "invar l"
        "invar r"
        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto
      hence v5: "e_less_eq e lp"
        by (metis e_less_eq_lem1)
      hence v6: "e \<le> (fst (p_unwrap lp))"
        by (cases lp) auto
      have "(Infty + listsum (map snd (\<alpha> l))) = (annot l)"
        by (metis add_0_left annot_correct v4(4) zero_def)
      hence v7:"\<not> e_less_eq e (annot l)"
        using v4(2) by simp
      have "\<forall>x\<in>set (\<alpha> l). snd x \<noteq> Infty"
        using g1asms v4(1) by simp
      hence v7: "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> l)). x < e"
        using v4(4) v7 assms(2)
        by(simp add: e_less_eq_annot)
      have v8:"map fst (map p_unwrap (map snd (\<alpha> s))) =
        map fst (map p_unwrap (map snd (\<alpha> l))) @ fst(p_unwrap lp) #
        map fst (map p_unwrap (map snd (\<alpha> r)))"
        using v4(1)
        by simp
      note distinct_sortet_list_app[of "map fst (map p_unwrap (map snd (\<alpha> s)))"
        "map fst (map p_unwrap (map snd (\<alpha> l)))" "fst(p_unwrap lp)"
        "map fst (map p_unwrap (map snd (\<alpha> r)))"]
      hence v9: "
        \<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). fst(p_unwrap lp) < x"
        using v4(1) g1asms v8
        by auto
      hence v10: " \<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). e < x"
        using v6 by auto
      have v11:
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> r))))"
        using v7 v10 v8 g1asms
        by auto
      from l_lp_r T1 g1asms show ?thesis
      proof (fold aluprio_insert_def, cases "e < fst (p_unwrap lp)")
        case True
        hence v12:
          "aluprio_insert splits annot isEmpty app consr s e a
            = app (consr (consr l () (LP e a)) () lp) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have v13:
          "\<alpha> (app (consr (consr l () (LP e a)) () lp) r)
            = \<alpha> l @ ((),(LP e a)) # ((), lp) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        have v14: "e = fst(p_unwrap (LP e a))" by simp
        have v15: "e \<notin> set (map fst (map p_unwrap (map snd(((),lp)#\<alpha> r))))"
          using v11(2) True by auto
        note map_of_distinct_upd2[OF v11(1) v15]
        thus
          "map_of (map p_unwrap (map snd (\<alpha>
              (aluprio_insert splits annot isEmpty app consr s e a))))
            = map_of (map p_unwrap (map snd (\<alpha> s)))(e \<mapsto> a)"
          using v12 v13 v4(1)
          by simp
      next
        case False
        hence v12:
          "aluprio_insert splits annot isEmpty app consr s e a
            = app (consr l () (LP e a)) r"
          using l_lp_r T1
          by (auto simp add: aluprio_defs)
        have v13:
          "\<alpha> (app (consr l () (LP e a)) r) = \<alpha> l @ ((),(LP e a)) # \<alpha> r"
          using v4(4,5) by (auto simp add: app_correct consr_correct)
        have v14: "e = fst(p_unwrap lp)"
          using False v5 by (cases lp) auto
        note v15 = map_of_distinct_upd3[OF v11(1) v11(2)]
        have v16:"(map p_unwrap (map snd (\<alpha> s))) =
          (map p_unwrap (map snd (\<alpha> l))) @ (e,snd(p_unwrap lp)) #
          (map p_unwrap (map snd (\<alpha> r)))"
          using v4(1) v14
          by simp
        note v15[of a "snd(p_unwrap lp)"]
        thus
          "map_of (map p_unwrap (map snd (\<alpha>
              (aluprio_insert splits annot isEmpty app consr s e a))))
            = map_of (map p_unwrap (map snd (\<alpha> s)))(e \<mapsto> a)"
          using v12 v13 v16
          by simp
      qed
    qed
  qed
qed

subsubsection "Prio"
lemma aluprio_prio_correct:
  assumes
  "al_splits \<alpha> invar splits"
  "al_annot \<alpha> invar annot"
  "al_isEmpty \<alpha> invar isEmpty"
  shows
  "uprio_prio (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_prio splits annot isEmpty)"
proof -
  interpret al_splits \<alpha> invar splits by fact
  interpret al_annot \<alpha> invar annot by fact
  interpret al_isEmpty \<alpha> invar isEmpty by fact
  show ?thesis
  proof (unfold_locales)
    fix s e
    assume inv1: "aluprio_invar \<alpha> invar s"
    hence sinv: "invar s"
      "(\<forall> x\<in>set (\<alpha> s). snd x\<noteq>Infty)"
      "sorted (map fst (map p_unwrap (map snd (\<alpha> s))))"
      "distinct (map fst (map p_unwrap (map snd (\<alpha> s))))"
      by (auto simp add: aluprio_defs)
    show "aluprio_prio splits annot isEmpty s e = aluprio_\<alpha> \<alpha> s e"
    proof(cases "e_less_eq e (annot s) \<and> \<not> isEmpty s")
      case False note F1 = this
      thus ?thesis
      proof(cases "isEmpty s")
        case True
        hence "\<alpha> s = []"
          using sinv isEmpty_correct by simp
        hence "aluprio_\<alpha> \<alpha> s = empty" by (simp add:aluprio_defs)
        hence "aluprio_\<alpha> \<alpha> s e = None" by simp
        thus "aluprio_prio splits annot isEmpty s e = aluprio_\<alpha> \<alpha> s e"
          using F1
          by (auto simp add: aluprio_defs)
      next
        case False
        hence v3:"\<not> e_less_eq e (annot s)"  using F1 by simp
        note v4=e_less_eq_annot[OF assms(2)]
        note v4[OF sinv(1) sinv(2) v3]
        hence v5:"e\<notin>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> s))"
          by auto
        hence "map_of (map (p_unwrap \<circ> snd) (\<alpha> s)) e = None"
          using map_of_eq_None_iff
          by (metis map_map map_of_eq_None_iff set_map v5)
        thus "aluprio_prio splits annot isEmpty s e = aluprio_\<alpha> \<alpha> s e"
          using F1
          by (auto simp add: aluprio_defs)
      qed
    next
      case True note T1 = this
      obtain l uu lp r where
        l_lp_r: "(splits (e_less_eq e) Infty s) = (l, ((), lp), r) "
        by (cases "splits (e_less_eq e) Infty s", auto)
      note v2 = splits_correct[of s "e_less_eq e" Infty l "()" lp r]
      have
        v3: "invar s"
        "\<not> e_less_eq e Infty"
        "e_less_eq e (Infty + listsum (map snd (\<alpha> s)))"
        using T1 sinv annot_correct
        by (auto simp add: plus_def)
      have
        v4: "\<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
        "\<not> e_less_eq e (Infty + listsum (map snd (\<alpha> l)))"
        "e_less_eq e (Infty + listsum (map snd (\<alpha> l)) + lp)"
        "invar l"
        "invar r"
        using v2[OF v3(1) _ v3(2) v3(3) l_lp_r] e_less_eq_mon(1) by auto
      hence v5: "e_less_eq e lp"
        by (metis e_less_eq_lem1)
      hence v6: "e \<le> (fst (p_unwrap lp))"
        by (cases lp) auto
      have "(Infty + listsum (map snd (\<alpha> l))) = (annot l)"
        by (metis add_0_left annot_correct v4(4) zero_def)
      hence v7:"\<not> e_less_eq e (annot l)"
        using v4(2) by simp
      have "\<forall>x\<in>set (\<alpha> l). snd x \<noteq> Infty"
        using sinv v4(1) by simp
      hence v7: "\<forall>x \<in> set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> l)). x < e"
        using v4(4) v7 assms(2)
        by(simp add: e_less_eq_annot)
      have v8:"map fst (map p_unwrap (map snd (\<alpha> s))) =
        map fst (map p_unwrap (map snd (\<alpha> l))) @ fst(p_unwrap lp) #
        map fst (map p_unwrap (map snd (\<alpha> r)))"
        using v4(1)
        by simp
      note distinct_sortet_list_app[of "map fst (map p_unwrap (map snd (\<alpha> s)))"
        "map fst (map p_unwrap (map snd (\<alpha> l)))" "fst(p_unwrap lp)"
        "map fst (map p_unwrap (map snd (\<alpha> r)))"]
      hence v9:
        "\<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). fst(p_unwrap lp) < x"
        using v4(1) sinv v8
        by auto
      hence v10: " \<forall> x\<in>set (map (fst \<circ> (p_unwrap \<circ> snd)) (\<alpha> r)). e < x"
        using v6 by auto
      have v11:
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> l))))"
        "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> r))))"
        using v7 v10 v8 sinv
        by auto
      from l_lp_r T1 sinv show ?thesis
      proof (cases "e = fst (p_unwrap lp)")
        case False
        have v12: "e \<notin> set (map fst (map p_unwrap (map snd(\<alpha> s))))"
          using v11 False v4(1) by auto
        hence "map_of (map (p_unwrap \<circ> snd) (\<alpha> s)) e = None"
          using map_of_eq_None_iff
          by (metis map_map map_of_eq_None_iff set_map v12)
        thus ?thesis
          using T1 False l_lp_r
          by (auto simp add: aluprio_defs)
      next
        case True
        have v12: "map (p_unwrap \<circ> snd) (\<alpha> s) =
          map p_unwrap (map snd (\<alpha> l)) @ (e,snd (p_unwrap lp)) #
          map p_unwrap (map snd (\<alpha> r))"
          using v4(1) True by simp
        note map_of_distinct_lookup[OF v11]
        hence
          "map_of (map (p_unwrap \<circ> snd) (\<alpha> s)) e = Some (snd (p_unwrap lp))"
          using v12 by simp
        thus ?thesis
          using T1 True l_lp_r
          by (auto simp add: aluprio_defs)
      qed
    qed
  qed
qed

subsubsection "Pop"

lemma aluprio_pop_correct:
  assumes "al_splits \<alpha> invar splits"
  "al_annot \<alpha> invar annot"
  "al_app \<alpha> invar app"
  shows
  "uprio_pop (aluprio_\<alpha> \<alpha>) (aluprio_invar \<alpha> invar) (aluprio_pop splits annot app)"
proof -
  interpret al_splits \<alpha> invar splits by fact
  interpret al_annot \<alpha> invar annot by fact
  interpret al_app \<alpha> invar app by fact
  show ?thesis
  proof (unfold_locales)
    fix s e a s'
    assume A: "aluprio_invar \<alpha> invar s"
      "aluprio_\<alpha> \<alpha> s \<noteq> empty"
      "aluprio_pop splits annot app s = (e, a, s')"
    hence v1: "\<alpha> s \<noteq> []"
      by (auto simp add: aluprio_defs)
    obtain l lp r where
      l_lp_r: "splits (\<lambda> x. x\<le>annot s) Infty s = (l,((),lp),r)"
      by (cases "splits (\<lambda> x. x\<le>annot s) Infty s", auto)
    have invs:
      "invar s"
      "(\<forall>x\<in>set (\<alpha> s). snd x \<noteq> Infty)"
      "sorted (map fst (map p_unwrap (map snd (\<alpha> s))))"
      "distinct (map fst (map p_unwrap (map snd (\<alpha> s))))"
      using A by (auto simp add:aluprio_defs)
    note a1 = annot_inf[of invar s \<alpha> annot]
    note a1[OF invs(1) invs(2) assms(2)]
    hence v2: "annot s \<noteq> Infty"
      using v1 by simp
    hence v3:
      "\<not> Infty \<le> annot s"
      by(cases "annot s") (auto simp add: plesseq_def)
    have v4: "annot s = listsum (map snd (\<alpha> s))"
      by (auto simp add: annot_correct invs(1))
    hence
      v5:
      "(Infty + listsum (map snd (\<alpha> s))) \<le> annot s"
      by (auto simp add: plus_def)
    note p_mon = p_less_eq_mon[of _ "annot s"]
    note v6 = splits_correct[OF invs(1)]
    note v7 = v6[of "\<lambda> x. x \<le> annot s"]
    note v7[OF _ v3 v5 l_lp_r] p_mon
    hence v8:
      " \<alpha> s = \<alpha> l @ ((), lp) # \<alpha> r"
      "\<not> Infty + listsum (map snd (\<alpha> l)) \<le> annot s"
      "Infty + listsum (map snd (\<alpha> l)) + lp \<le> annot s"
      "invar l"
      "invar r"
      by auto
    hence v9: "lp \<noteq> Infty"
      using invs(2) by auto
    hence v10:
      "s' = app l r"
      "(e,a) = p_unwrap lp"
      using l_lp_r A(3)
      apply (auto simp add: aluprio_defs)
      apply (cases lp)
      apply auto
      apply (cases lp)
      apply auto
      done
    have "lp \<le> annot s"
      using v8(2,3) p_less_eq_lem1
      by auto
    hence v11: "a \<le> snd (p_unwrap (annot s))"
      using v10(2) v2 v9
      apply (cases "annot s")
      apply auto
      apply (cases lp)
      apply (auto simp add: plesseq_def)
      done
    note listsum_less_elems[OF invs(2)]
    hence v12: "\<forall>y\<in>set (map snd (map p_unwrap (map snd (\<alpha> s)))). a \<le> y"
      using v4 v11 by auto
    have "ran (aluprio_\<alpha> \<alpha> s) = set (map snd (map p_unwrap (map snd (\<alpha> s))))"
      using ran_distinct[OF invs(4)]
      apply (unfold aluprio_defs)
      apply (simp only: set_map)
      done
    hence ziel1: "\<forall>y\<in>ran (aluprio_\<alpha> \<alpha> s). a \<le> y"
      using v12 by simp
    have v13:
      "map p_unwrap (map snd (\<alpha> s))
        = map p_unwrap (map  snd (\<alpha> l)) @ (e,a) # map p_unwrap (map snd (\<alpha> r))"
      using v8(1) v10 by auto
     hence v14:
      "map fst (map p_unwrap (map snd (\<alpha> s)))
         = map fst (map p_unwrap (map snd (\<alpha> l))) @ e
             # map fst (map p_unwrap (map snd (\<alpha> r)))"
       by auto
    hence v15:
      "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> l))))"
      "e \<notin> set (map fst (map p_unwrap (map snd (\<alpha> r))))"
      using invs(4) by auto
    note map_of_distinct_lookup[OF v15]
    note this[of a]
    hence ziel2: "aluprio_\<alpha> \<alpha> s e = Some a"
      using  v13
      by (unfold aluprio_defs, auto)
    have v16:
      "\<alpha> s' = \<alpha> l @ \<alpha> r"
      "invar s'"
      using v8(4,5) app_correct v10 by auto
    note map_of_distinct_upd4[OF v15]
    note this[of a]
    hence
      ziel3: "aluprio_\<alpha> \<alpha> s' = (aluprio_\<alpha> \<alpha> s)(e := None)"
      unfolding aluprio_defs
      using v16(1) v13 by auto
    have ziel4: "aluprio_invar \<alpha> invar s'"
      using v16 v8(1) invs(2,3,4)
      unfolding aluprio_defs
      by (auto simp add: sorted_Cons sorted_append)

    show "aluprio_invar \<alpha> invar s' \<and>
          aluprio_\<alpha> \<alpha> s' = (aluprio_\<alpha> \<alpha> s)(e := None) \<and>
          aluprio_\<alpha> \<alpha> s e = Some a \<and> (\<forall>y\<in>ran (aluprio_\<alpha> \<alpha> s). a \<le> y)"
      using ziel1 ziel2 ziel3 ziel4 by simp
  qed
qed

lemmas aluprio_correct =
  aluprio_finite_correct
  aluprio_empty_correct
  aluprio_isEmpty_correct
  aluprio_insert_correct
  aluprio_pop_correct
  aluprio_prio_correct

locale aluprio_defs = StdALDefs ops
  for ops :: "(unit,('e::linorder,'a::linorder) LP,'s) alist_ops"
begin
  definition [icf_rec_def]: "aluprio_ops \<equiv> \<lparr>
    upr_\<alpha> = aluprio_\<alpha> \<alpha>,
    upr_invar = aluprio_invar \<alpha> invar,
    upr_empty = aluprio_empty empty,
    upr_isEmpty = aluprio_isEmpty isEmpty,
    upr_insert = aluprio_insert splits annot isEmpty app consr,
    upr_pop = aluprio_pop splits annot app,
    upr_prio = aluprio_prio splits annot isEmpty
    \<rparr>"

end

locale aluprio = aluprio_defs ops + StdAL ops
  for ops :: "(unit,('e::linorder,'a::linorder) LP,'s) alist_ops"
begin
  lemma aluprio_ops_impl: "StdUprio aluprio_ops"
    apply (rule StdUprio.intro)
    apply (simp_all add: icf_rec_unf)
    apply (rule aluprio_correct)
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    apply (rule aluprio_correct, unfold_locales) []
    done
end

end


(*  Title:      HOL/Num.thy
    Author:     Florian Haftmann
    Author:     Brian Huffman
*)

section \<open>Binary Numerals\<close>

theory Num
  imports BNF_Least_Fixpoint Transfer
begin

subsection \<open>The \<open>num\<close> type\<close>

datatype num = One | Bit0 num | Bit1 num

text \<open>Increment function for type @{typ num}\<close>

primrec inc :: "num \<Rightarrow> num"
  where
    "inc One = Bit0 One"
  | "inc (Bit0 x) = Bit1 x"
  | "inc (Bit1 x) = Bit0 (inc x)"

text \<open>Converting between type @{typ num} and type @{typ nat}\<close>

primrec nat_of_num :: "num \<Rightarrow> nat"
  where
    "nat_of_num One = Suc 0"
  | "nat_of_num (Bit0 x) = nat_of_num x + nat_of_num x"
  | "nat_of_num (Bit1 x) = Suc (nat_of_num x + nat_of_num x)"

primrec num_of_nat :: "nat \<Rightarrow> num"
  where
    "num_of_nat 0 = One"
  | "num_of_nat (Suc n) = (if 0 < n then inc (num_of_nat n) else One)"

lemma nat_of_num_pos: "0 < nat_of_num x"
  by (induct x) simp_all

lemma nat_of_num_neq_0: " nat_of_num x \<noteq> 0"
  by (induct x) simp_all

lemma nat_of_num_inc: "nat_of_num (inc x) = Suc (nat_of_num x)"
  by (induct x) simp_all

lemma num_of_nat_double: "0 < n \<Longrightarrow> num_of_nat (n + n) = Bit0 (num_of_nat n)"
  by (induct n) simp_all

text \<open>Type @{typ num} is isomorphic to the strictly positive natural numbers.\<close>

lemma nat_of_num_inverse: "num_of_nat (nat_of_num x) = x"
  by (induct x) (simp_all add: num_of_nat_double nat_of_num_pos)

lemma num_of_nat_inverse: "0 < n \<Longrightarrow> nat_of_num (num_of_nat n) = n"
  by (induct n) (simp_all add: nat_of_num_inc)

lemma num_eq_iff: "x = y \<longleftrightarrow> nat_of_num x = nat_of_num y"
  apply safe
  apply (drule arg_cong [where f=num_of_nat])
  apply (simp add: nat_of_num_inverse)
  done

lemma num_induct [case_names One inc]:
  fixes P :: "num \<Rightarrow> bool"
  assumes One: "P One"
    and inc: "\<And>x. P x \<Longrightarrow> P (inc x)"
  shows "P x"
proof -
  obtain n where n: "Suc n = nat_of_num x"
    by (cases "nat_of_num x") (simp_all add: nat_of_num_neq_0)
  have "P (num_of_nat (Suc n))"
  proof (induct n)
    case 0
    from One show ?case by simp
  next
    case (Suc n)
    then have "P (inc (num_of_nat (Suc n)))" by (rule inc)
    then show "P (num_of_nat (Suc (Suc n)))" by simp
  qed
  with n show "P x"
    by (simp add: nat_of_num_inverse)
qed

text \<open>
  From now on, there are two possible models for @{typ num}: as positive
  naturals (rule \<open>num_induct\<close>) and as digit representation (rules
  \<open>num.induct\<close>, \<open>num.cases\<close>).
\<close>

subsection \<open>Numeral operations\<close>

instantiation num :: "{plus,times,linorder}"
begin

definition [code del]: "m + n = num_of_nat (nat_of_num m + nat_of_num n)"

definition [code del]: "m * n = num_of_nat (nat_of_num m * nat_of_num n)"

definition [code del]: "m \<le> n \<longleftrightarrow> nat_of_num m \<le> nat_of_num n"

definition [code del]: "m < n \<longleftrightarrow> nat_of_num m < nat_of_num n"

instance
  by standard (auto simp add: less_num_def less_eq_num_def num_eq_iff)

end

lemma nat_of_num_add: "nat_of_num (x + y) = nat_of_num x + nat_of_num y"
  unfolding plus_num_def
  by (intro num_of_nat_inverse add_pos_pos nat_of_num_pos)

lemma nat_of_num_mult: "nat_of_num (x * y) = nat_of_num x * nat_of_num y"
  unfolding times_num_def
  by (intro num_of_nat_inverse mult_pos_pos nat_of_num_pos)

lemma add_num_simps [simp, code]:
  "One + One = Bit0 One"
  "One + Bit0 n = Bit1 n"
  "One + Bit1 n = Bit0 (n + One)"
  "Bit0 m + One = Bit1 m"
  "Bit0 m + Bit0 n = Bit0 (m + n)"
  "Bit0 m + Bit1 n = Bit1 (m + n)"
  "Bit1 m + One = Bit0 (m + One)"
  "Bit1 m + Bit0 n = Bit1 (m + n)"
  "Bit1 m + Bit1 n = Bit0 (m + n + One)"
  by (simp_all add: num_eq_iff nat_of_num_add)

lemma mult_num_simps [simp, code]:
  "m * One = m"
  "One * n = n"
  "Bit0 m * Bit0 n = Bit0 (Bit0 (m * n))"
  "Bit0 m * Bit1 n = Bit0 (m * Bit1 n)"
  "Bit1 m * Bit0 n = Bit0 (Bit1 m * n)"
  "Bit1 m * Bit1 n = Bit1 (m + n + Bit0 (m * n))"
  by (simp_all add: num_eq_iff nat_of_num_add nat_of_num_mult distrib_right distrib_left)

lemma eq_num_simps:
  "One = One \<longleftrightarrow> True"
  "One = Bit0 n \<longleftrightarrow> False"
  "One = Bit1 n \<longleftrightarrow> False"
  "Bit0 m = One \<longleftrightarrow> False"
  "Bit1 m = One \<longleftrightarrow> False"
  "Bit0 m = Bit0 n \<longleftrightarrow> m = n"
  "Bit0 m = Bit1 n \<longleftrightarrow> False"
  "Bit1 m = Bit0 n \<longleftrightarrow> False"
  "Bit1 m = Bit1 n \<longleftrightarrow> m = n"
  by simp_all

lemma le_num_simps [simp, code]:
  "One \<le> n \<longleftrightarrow> True"
  "Bit0 m \<le> One \<longleftrightarrow> False"
  "Bit1 m \<le> One \<longleftrightarrow> False"
  "Bit0 m \<le> Bit0 n \<longleftrightarrow> m \<le> n"
  "Bit0 m \<le> Bit1 n \<longleftrightarrow> m \<le> n"
  "Bit1 m \<le> Bit1 n \<longleftrightarrow> m \<le> n"
  "Bit1 m \<le> Bit0 n \<longleftrightarrow> m < n"
  using nat_of_num_pos [of n] nat_of_num_pos [of m]
  by (auto simp add: less_eq_num_def less_num_def)

lemma less_num_simps [simp, code]:
  "m < One \<longleftrightarrow> False"
  "One < Bit0 n \<longleftrightarrow> True"
  "One < Bit1 n \<longleftrightarrow> True"
  "Bit0 m < Bit0 n \<longleftrightarrow> m < n"
  "Bit0 m < Bit1 n \<longleftrightarrow> m \<le> n"
  "Bit1 m < Bit1 n \<longleftrightarrow> m < n"
  "Bit1 m < Bit0 n \<longleftrightarrow> m < n"
  using nat_of_num_pos [of n] nat_of_num_pos [of m]
  by (auto simp add: less_eq_num_def less_num_def)

lemma le_num_One_iff: "x \<le> num.One \<longleftrightarrow> x = num.One"
  by (simp add: antisym_conv)

text \<open>Rules using \<open>One\<close> and \<open>inc\<close> as constructors.\<close>

lemma add_One: "x + One = inc x"
  by (simp add: num_eq_iff nat_of_num_add nat_of_num_inc)

lemma add_One_commute: "One + n = n + One"
  by (induct n) simp_all

lemma add_inc: "x + inc y = inc (x + y)"
  by (simp add: num_eq_iff nat_of_num_add nat_of_num_inc)

lemma mult_inc: "x * inc y = x * y + x"
  by (simp add: num_eq_iff nat_of_num_mult nat_of_num_add nat_of_num_inc)

text \<open>The @{const num_of_nat} conversion.\<close>

lemma num_of_nat_One: "n \<le> 1 \<Longrightarrow> num_of_nat n = One"
  by (cases n) simp_all

lemma num_of_nat_plus_distrib:
  "0 < m \<Longrightarrow> 0 < n \<Longrightarrow> num_of_nat (m + n) = num_of_nat m + num_of_nat n"
  by (induct n) (auto simp add: add_One add_One_commute add_inc)

text \<open>A double-and-decrement function.\<close>

primrec BitM :: "num \<Rightarrow> num"
  where
    "BitM One = One"
  | "BitM (Bit0 n) = Bit1 (BitM n)"
  | "BitM (Bit1 n) = Bit1 (Bit0 n)"

lemma BitM_plus_one: "BitM n + One = Bit0 n"
  by (induct n) simp_all

lemma one_plus_BitM: "One + BitM n = Bit0 n"
  unfolding add_One_commute BitM_plus_one ..

text \<open>Squaring and exponentiation.\<close>

primrec sqr :: "num \<Rightarrow> num"
  where
    "sqr One = One"
  | "sqr (Bit0 n) = Bit0 (Bit0 (sqr n))"
  | "sqr (Bit1 n) = Bit1 (Bit0 (sqr n + n))"

primrec pow :: "num \<Rightarrow> num \<Rightarrow> num"
  where
    "pow x One = x"
  | "pow x (Bit0 y) = sqr (pow x y)"
  | "pow x (Bit1 y) = sqr (pow x y) * x"

lemma nat_of_num_sqr: "nat_of_num (sqr x) = nat_of_num x * nat_of_num x"
  by (induct x) (simp_all add: algebra_simps nat_of_num_add)

lemma sqr_conv_mult: "sqr x = x * x"
  by (simp add: num_eq_iff nat_of_num_sqr nat_of_num_mult)

subsection \<open>Binary numerals\<close>

text \<open>
  We embed binary representations into a generic algebraic
  structure using \<open>numeral\<close>.
\<close>

class numeral = one + semigroup_add
begin

primrec numeral :: "num \<Rightarrow> 'a"
  where
    numeral_One: "numeral One = 1"
  | numeral_Bit0: "numeral (Bit0 n) = numeral n + numeral n"
  | numeral_Bit1: "numeral (Bit1 n) = numeral n + numeral n + 1"

lemma numeral_code [code]:
  "numeral One = 1"
  "numeral (Bit0 n) = (let m = numeral n in m + m)"
  "numeral (Bit1 n) = (let m = numeral n in m + m + 1)"
  by (simp_all add: Let_def)

lemma one_plus_numeral_commute: "1 + numeral x = numeral x + 1"
proof (induct x)
  case One
  then show ?case by simp
next
  case Bit0
  then show ?case by (simp add: add.assoc [symmetric]) (simp add: add.assoc)
next
  case Bit1
  then show ?case by (simp add: add.assoc [symmetric]) (simp add: add.assoc)
qed

lemma numeral_inc: "numeral (inc x) = numeral x + 1"
proof (induct x)
  case One
  then show ?case by simp
next
  case Bit0
  then show ?case by simp
next
  case (Bit1 x)
  have "numeral x + (1 + numeral x) + 1 = numeral x + (numeral x + 1) + 1"
    by (simp only: one_plus_numeral_commute)
  with Bit1 show ?case
    by (simp add: add.assoc)
qed

declare numeral.simps [simp del]

abbreviation "Numeral1 \<equiv> numeral One"

declare numeral_One [code_post]

end

text \<open>Numeral syntax.\<close>

syntax
  "_Numeral" :: "num_const \<Rightarrow> 'a"    ("_")

ML_file "Tools/numeral.ML"

parse_translation \<open>
  let
    fun numeral_tr [(c as Const (@{syntax_const "_constrain"}, _)) $ t $ u] =
          c $ numeral_tr [t] $ u
      | numeral_tr [Const (num, _)] =
          (Numeral.mk_number_syntax o #value o Lexicon.read_num) num
      | numeral_tr ts = raise TERM ("numeral_tr", ts);
  in [(@{syntax_const "_Numeral"}, K numeral_tr)] end
\<close>

typed_print_translation \<open>
  let
    fun num_tr' ctxt T [n] =
      let
        val k = Numeral.dest_num_syntax n;
        val t' =
          Syntax.const @{syntax_const "_Numeral"} $
            Syntax.free (string_of_int k);
      in
        (case T of
          Type (@{type_name fun}, [_, T']) =>
            if Printer.type_emphasis ctxt T' then
              Syntax.const @{syntax_const "_constrain"} $ t' $
                Syntax_Phases.term_of_typ ctxt T'
            else t'
        | _ => if T = dummyT then t' else raise Match)
      end;
  in
   [(@{const_syntax numeral}, num_tr')]
  end
\<close>

subsection \<open>Class-specific numeral rules\<close>

text \<open>@{const numeral} is a morphism.\<close>

subsubsection \<open>Structures with addition: class \<open>numeral\<close>\<close>

context numeral
begin

lemma numeral_add: "numeral (m + n) = numeral m + numeral n"
  by (induct n rule: num_induct)
    (simp_all only: numeral_One add_One add_inc numeral_inc add.assoc)

lemma numeral_plus_numeral: "numeral m + numeral n = numeral (m + n)"
  by (rule numeral_add [symmetric])

lemma numeral_plus_one: "numeral n + 1 = numeral (n + One)"
  using numeral_add [of n One] by (simp add: numeral_One)

lemma one_plus_numeral: "1 + numeral n = numeral (One + n)"
  using numeral_add [of One n] by (simp add: numeral_One)

lemma one_add_one: "1 + 1 = 2"
  using numeral_add [of One One] by (simp add: numeral_One)

lemmas add_numeral_special =
  numeral_plus_one one_plus_numeral one_add_one

end

subsubsection \<open>Structures with negation: class \<open>neg_numeral\<close>\<close>

class neg_numeral = numeral + group_add
begin

lemma uminus_numeral_One: "- Numeral1 = - 1"
  by (simp add: numeral_One)

text \<open>Numerals form an abelian subgroup.\<close>

inductive is_num :: "'a \<Rightarrow> bool"
  where
    "is_num 1"
  | "is_num x \<Longrightarrow> is_num (- x)"
  | "is_num x \<Longrightarrow> is_num y \<Longrightarrow> is_num (x + y)"

lemma is_num_numeral: "is_num (numeral k)"
  by (induct k) (simp_all add: numeral.simps is_num.intros)

lemma is_num_add_commute: "is_num x \<Longrightarrow> is_num y \<Longrightarrow> x + y = y + x"
  apply (induct x rule: is_num.induct)
    apply (induct y rule: is_num.induct)
      apply simp
     apply (rule_tac a=x in add_left_imp_eq)
     apply (rule_tac a=x in add_right_imp_eq)
     apply (simp add: add.assoc)
    apply (simp add: add.assoc [symmetric])
    apply (simp add: add.assoc)
   apply (rule_tac a=x in add_left_imp_eq)
   apply (rule_tac a=x in add_right_imp_eq)
   apply (simp add: add.assoc)
  apply (simp add: add.assoc)
  apply (simp add: add.assoc [symmetric])
  done

lemma is_num_add_left_commute: "is_num x \<Longrightarrow> is_num y \<Longrightarrow> x + (y + z) = y + (x + z)"
  by (simp only: add.assoc [symmetric] is_num_add_commute)

lemmas is_num_normalize =
  add.assoc is_num_add_commute is_num_add_left_commute
  is_num.intros is_num_numeral
  minus_add

definition dbl :: "'a \<Rightarrow> 'a"
  where "dbl x = x + x"

definition dbl_inc :: "'a \<Rightarrow> 'a"
  where "dbl_inc x = x + x + 1"

definition dbl_dec :: "'a \<Rightarrow> 'a"
  where "dbl_dec x = x + x - 1"

definition sub :: "num \<Rightarrow> num \<Rightarrow> 'a"
  where "sub k l = numeral k - numeral l"

lemma numeral_BitM: "numeral (BitM n) = numeral (Bit0 n) - 1"
  by (simp only: BitM_plus_one [symmetric] numeral_add numeral_One eq_diff_eq)

lemma dbl_simps [simp]:
  "dbl (- numeral k) = - dbl (numeral k)"
  "dbl 0 = 0"
  "dbl 1 = 2"
  "dbl (- 1) = - 2"
  "dbl (numeral k) = numeral (Bit0 k)"
  by (simp_all add: dbl_def numeral.simps minus_add)

lemma dbl_inc_simps [simp]:
  "dbl_inc (- numeral k) = - dbl_dec (numeral k)"
  "dbl_inc 0 = 1"
  "dbl_inc 1 = 3"
  "dbl_inc (- 1) = - 1"
  "dbl_inc (numeral k) = numeral (Bit1 k)"
  by (simp_all add: dbl_inc_def dbl_dec_def numeral.simps numeral_BitM is_num_normalize algebra_simps
      del: add_uminus_conv_diff)

lemma dbl_dec_simps [simp]:
  "dbl_dec (- numeral k) = - dbl_inc (numeral k)"
  "dbl_dec 0 = - 1"
  "dbl_dec 1 = 1"
  "dbl_dec (- 1) = - 3"
  "dbl_dec (numeral k) = numeral (BitM k)"
  by (simp_all add: dbl_dec_def dbl_inc_def numeral.simps numeral_BitM is_num_normalize)

lemma sub_num_simps [simp]:
  "sub One One = 0"
  "sub One (Bit0 l) = - numeral (BitM l)"
  "sub One (Bit1 l) = - numeral (Bit0 l)"
  "sub (Bit0 k) One = numeral (BitM k)"
  "sub (Bit1 k) One = numeral (Bit0 k)"
  "sub (Bit0 k) (Bit0 l) = dbl (sub k l)"
  "sub (Bit0 k) (Bit1 l) = dbl_dec (sub k l)"
  "sub (Bit1 k) (Bit0 l) = dbl_inc (sub k l)"
  "sub (Bit1 k) (Bit1 l) = dbl (sub k l)"
  by (simp_all add: dbl_def dbl_dec_def dbl_inc_def sub_def numeral.simps
    numeral_BitM is_num_normalize del: add_uminus_conv_diff add: diff_conv_add_uminus)

lemma add_neg_numeral_simps:
  "numeral m + - numeral n = sub m n"
  "- numeral m + numeral n = sub n m"
  "- numeral m + - numeral n = - (numeral m + numeral n)"
  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize
      del: add_uminus_conv_diff add: diff_conv_add_uminus)

lemma add_neg_numeral_special:
  "1 + - numeral m = sub One m"
  "- numeral m + 1 = sub One m"
  "numeral m + - 1 = sub m One"
  "- 1 + numeral n = sub n One"
  "- 1 + - numeral n = - numeral (inc n)"
  "- numeral m + - 1 = - numeral (inc m)"
  "1 + - 1 = 0"
  "- 1 + 1 = 0"
  "- 1 + - 1 = - 2"
  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize right_minus numeral_inc
      del: add_uminus_conv_diff add: diff_conv_add_uminus)

lemma diff_numeral_simps:
  "numeral m - numeral n = sub m n"
  "numeral m - - numeral n = numeral (m + n)"
  "- numeral m - numeral n = - numeral (m + n)"
  "- numeral m - - numeral n = sub n m"
  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize
      del: add_uminus_conv_diff add: diff_conv_add_uminus)

lemma diff_numeral_special:
  "1 - numeral n = sub One n"
  "numeral m - 1 = sub m One"
  "1 - - numeral n = numeral (One + n)"
  "- numeral m - 1 = - numeral (m + One)"
  "- 1 - numeral n = - numeral (inc n)"
  "numeral m - - 1 = numeral (inc m)"
  "- 1 - - numeral n = sub n One"
  "- numeral m - - 1 = sub One m"
  "1 - 1 = 0"
  "- 1 - 1 = - 2"
  "1 - - 1 = 2"
  "- 1 - - 1 = 0"
  by (simp_all add: sub_def numeral_add numeral.simps is_num_normalize numeral_inc
      del: add_uminus_conv_diff add: diff_conv_add_uminus)

end

subsubsection \<open>Structures with multiplication: class \<open>semiring_numeral\<close>\<close>

class semiring_numeral = semiring + monoid_mult
begin

subclass numeral ..

lemma numeral_mult: "numeral (m * n) = numeral m * numeral n"
  by (induct n rule: num_induct)
    (simp_all add: numeral_One mult_inc numeral_inc numeral_add distrib_left)

lemma numeral_times_numeral: "numeral m * numeral n = numeral (m * n)"
  by (rule numeral_mult [symmetric])

lemma mult_2: "2 * z = z + z"
  by (simp add: one_add_one [symmetric] distrib_right)

lemma mult_2_right: "z * 2 = z + z"
  by (simp add: one_add_one [symmetric] distrib_left)

end

subsubsection \<open>Structures with a zero: class \<open>semiring_1\<close>\<close>

context semiring_1
begin

subclass semiring_numeral ..

lemma of_nat_numeral [simp]: "of_nat (numeral n) = numeral n"
  by (induct n) (simp_all only: numeral.simps numeral_class.numeral.simps of_nat_add of_nat_1)

lemma numeral_unfold_funpow:
  "numeral k = (op + 1 ^^ numeral k) 0"
  unfolding of_nat_def [symmetric] by simp

end

lemma transfer_rule_numeral:
  fixes R :: "'a::semiring_1 \<Rightarrow> 'b::semiring_1 \<Rightarrow> bool"
  assumes [transfer_rule]: "R 0 0" "R 1 1"
    "rel_fun R (rel_fun R R) plus plus"
  shows "rel_fun HOL.eq R numeral numeral"
  apply (subst (2) numeral_unfold_funpow [abs_def])
  apply (subst (1) numeral_unfold_funpow [abs_def])
  apply transfer_prover
  done

lemma nat_of_num_numeral [code_abbrev]: "nat_of_num = numeral"
proof
  fix n
  have "numeral n = nat_of_num n"
    by (induct n) (simp_all add: numeral.simps)
  then show "nat_of_num n = numeral n"
    by simp
qed

lemma nat_of_num_code [code]:
  "nat_of_num One = 1"
  "nat_of_num (Bit0 n) = (let m = nat_of_num n in m + m)"
  "nat_of_num (Bit1 n) = (let m = nat_of_num n in Suc (m + m))"
  by (simp_all add: Let_def)

subsubsection \<open>Equality: class \<open>semiring_char_0\<close>\<close>

context semiring_char_0
begin

lemma numeral_eq_iff: "numeral m = numeral n \<longleftrightarrow> m = n"
  by (simp only: of_nat_numeral [symmetric] nat_of_num_numeral [symmetric]
    of_nat_eq_iff num_eq_iff)

lemma numeral_eq_one_iff: "numeral n = 1 \<longleftrightarrow> n = One"
  by (rule numeral_eq_iff [of n One, unfolded numeral_One])

lemma one_eq_numeral_iff: "1 = numeral n \<longleftrightarrow> One = n"
  by (rule numeral_eq_iff [of One n, unfolded numeral_One])

lemma numeral_neq_zero: "numeral n \<noteq> 0"
  by (simp add: of_nat_numeral [symmetric] nat_of_num_numeral [symmetric] nat_of_num_pos)

lemma zero_neq_numeral: "0 \<noteq> numeral n"
  unfolding eq_commute [of 0] by (rule numeral_neq_zero)

lemmas eq_numeral_simps [simp] =
  numeral_eq_iff
  numeral_eq_one_iff
  one_eq_numeral_iff
  numeral_neq_zero
  zero_neq_numeral

end

subsubsection \<open>Comparisons: class \<open>linordered_semidom\<close>\<close>

text \<open>Could be perhaps more general than here.\<close>

context linordered_semidom
begin

lemma numeral_le_iff: "numeral m \<le> numeral n \<longleftrightarrow> m \<le> n"
proof -
  have "of_nat (numeral m) \<le> of_nat (numeral n) \<longleftrightarrow> m \<le> n"
    by (simp only: less_eq_num_def nat_of_num_numeral of_nat_le_iff)
  then show ?thesis by simp
qed

lemma one_le_numeral: "1 \<le> numeral n"
  using numeral_le_iff [of One n] by (simp add: numeral_One)

lemma numeral_le_one_iff: "numeral n \<le> 1 \<longleftrightarrow> n \<le> One"
  using numeral_le_iff [of n One] by (simp add: numeral_One)

lemma numeral_less_iff: "numeral m < numeral n \<longleftrightarrow> m < n"
proof -
  have "of_nat (numeral m) < of_nat (numeral n) \<longleftrightarrow> m < n"
    unfolding less_num_def nat_of_num_numeral of_nat_less_iff ..
  then show ?thesis by simp
qed

lemma not_numeral_less_one: "\<not> numeral n < 1"
  using numeral_less_iff [of n One] by (simp add: numeral_One)

lemma one_less_numeral_iff: "1 < numeral n \<longleftrightarrow> One < n"
  using numeral_less_iff [of One n] by (simp add: numeral_One)

lemma zero_le_numeral: "0 \<le> numeral n"
  by (induct n) (simp_all add: numeral.simps)

lemma zero_less_numeral: "0 < numeral n"
  by (induct n) (simp_all add: numeral.simps add_pos_pos)

lemma not_numeral_le_zero: "\<not> numeral n \<le> 0"
  by (simp add: not_le zero_less_numeral)

lemma not_numeral_less_zero: "\<not> numeral n < 0"
  by (simp add: not_less zero_le_numeral)

lemmas le_numeral_extra =
  zero_le_one not_one_le_zero
  order_refl [of 0] order_refl [of 1]

lemmas less_numeral_extra =
  zero_less_one not_one_less_zero
  less_irrefl [of 0] less_irrefl [of 1]

lemmas le_numeral_simps [simp] =
  numeral_le_iff
  one_le_numeral
  numeral_le_one_iff
  zero_le_numeral
  not_numeral_le_zero

lemmas less_numeral_simps [simp] =
  numeral_less_iff
  one_less_numeral_iff
  not_numeral_less_one
  zero_less_numeral
  not_numeral_less_zero

lemma min_0_1 [simp]:
  fixes min' :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"
  defines "min' \<equiv> min"
  shows
    "min' 0 1 = 0"
    "min' 1 0 = 0"
    "min' 0 (numeral x) = 0"
    "min' (numeral x) 0 = 0"
    "min' 1 (numeral x) = 1"
    "min' (numeral x) 1 = 1"
  by (simp_all add: min'_def min_def le_num_One_iff)

lemma max_0_1 [simp]:
  fixes max' :: "'a \<Rightarrow> 'a \<Rightarrow> 'a"
  defines "max' \<equiv> max"
  shows
    "max' 0 1 = 1"
    "max' 1 0 = 1"
    "max' 0 (numeral x) = numeral x"
    "max' (numeral x) 0 = numeral x"
    "max' 1 (numeral x) = numeral x"
    "max' (numeral x) 1 = numeral x"
  by (simp_all add: max'_def max_def le_num_One_iff)

end

subsubsection \<open>Multiplication and negation: class \<open>ring_1\<close>\<close>

context ring_1
begin

subclass neg_numeral ..

lemma mult_neg_numeral_simps:
  "- numeral m * - numeral n = numeral (m * n)"
  "- numeral m * numeral n = - numeral (m * n)"
  "numeral m * - numeral n = - numeral (m * n)"
  by (simp_all only: mult_minus_left mult_minus_right minus_minus numeral_mult)

lemma mult_minus1 [simp]: "- 1 * z = - z"
  by (simp add: numeral.simps)

lemma mult_minus1_right [simp]: "z * - 1 = - z"
  by (simp add: numeral.simps)

end

subsubsection \<open>Equality using \<open>iszero\<close> for rings with non-zero characteristic\<close>

context ring_1
begin

definition iszero :: "'a \<Rightarrow> bool"
  where "iszero z \<longleftrightarrow> z = 0"

lemma iszero_0 [simp]: "iszero 0"
  by (simp add: iszero_def)

lemma not_iszero_1 [simp]: "\<not> iszero 1"
  by (simp add: iszero_def)

lemma not_iszero_Numeral1: "\<not> iszero Numeral1"
  by (simp add: numeral_One)

lemma not_iszero_neg_1 [simp]: "\<not> iszero (- 1)"
  by (simp add: iszero_def)

lemma not_iszero_neg_Numeral1: "\<not> iszero (- Numeral1)"
  by (simp add: numeral_One)

lemma iszero_neg_numeral [simp]: "iszero (- numeral w) \<longleftrightarrow> iszero (numeral w)"
  unfolding iszero_def by (rule neg_equal_0_iff_equal)

lemma eq_iff_iszero_diff: "x = y \<longleftrightarrow> iszero (x - y)"
  unfolding iszero_def by (rule eq_iff_diff_eq_0)

text \<open>
  The \<open>eq_numeral_iff_iszero\<close> lemmas are not declared \<open>[simp]\<close> by default,
  because for rings of characteristic zero, better simp rules are possible.
  For a type like integers mod \<open>n\<close>, type-instantiated versions of these rules
  should be added to the simplifier, along with a type-specific rule for
  deciding propositions of the form \<open>iszero (numeral w)\<close>.

  bh: Maybe it would not be so bad to just declare these as simp rules anyway?
  I should test whether these rules take precedence over the \<open>ring_char_0\<close>
  rules in the simplifier.
\<close>

lemma eq_numeral_iff_iszero:
  "numeral x = numeral y \<longleftrightarrow> iszero (sub x y)"
  "numeral x = - numeral y \<longleftrightarrow> iszero (numeral (x + y))"
  "- numeral x = numeral y \<longleftrightarrow> iszero (numeral (x + y))"
  "- numeral x = - numeral y \<longleftrightarrow> iszero (sub y x)"
  "numeral x = 1 \<longleftrightarrow> iszero (sub x One)"
  "1 = numeral y \<longleftrightarrow> iszero (sub One y)"
  "- numeral x = 1 \<longleftrightarrow> iszero (numeral (x + One))"
  "1 = - numeral y \<longleftrightarrow> iszero (numeral (One + y))"
  "numeral x = 0 \<longleftrightarrow> iszero (numeral x)"
  "0 = numeral y \<longleftrightarrow> iszero (numeral y)"
  "- numeral x = 0 \<longleftrightarrow> iszero (numeral x)"
  "0 = - numeral y \<longleftrightarrow> iszero (numeral y)"
  unfolding eq_iff_iszero_diff diff_numeral_simps diff_numeral_special
  by simp_all

end

subsubsection \<open>Equality and negation: class \<open>ring_char_0\<close>\<close>

context ring_char_0
begin

lemma not_iszero_numeral [simp]: "\<not> iszero (numeral w)"
  by (simp add: iszero_def)

lemma neg_numeral_eq_iff: "- numeral m = - numeral n \<longleftrightarrow> m = n"
  by simp

lemma numeral_neq_neg_numeral: "numeral m \<noteq> - numeral n"
  by (simp add: eq_neg_iff_add_eq_0 numeral_plus_numeral)

lemma neg_numeral_neq_numeral: "- numeral m \<noteq> numeral n"
  by (rule numeral_neq_neg_numeral [symmetric])

lemma zero_neq_neg_numeral: "0 \<noteq> - numeral n"
  by simp

lemma neg_numeral_neq_zero: "- numeral n \<noteq> 0"
  by simp

lemma one_neq_neg_numeral: "1 \<noteq> - numeral n"
  using numeral_neq_neg_numeral [of One n] by (simp add: numeral_One)

lemma neg_numeral_neq_one: "- numeral n \<noteq> 1"
  using neg_numeral_neq_numeral [of n One] by (simp add: numeral_One)

lemma neg_one_neq_numeral: "- 1 \<noteq> numeral n"
  using neg_numeral_neq_numeral [of One n] by (simp add: numeral_One)

lemma numeral_neq_neg_one: "numeral n \<noteq> - 1"
  using numeral_neq_neg_numeral [of n One] by (simp add: numeral_One)

lemma neg_one_eq_numeral_iff: "- 1 = - numeral n \<longleftrightarrow> n = One"
  using neg_numeral_eq_iff [of One n] by (auto simp add: numeral_One)

lemma numeral_eq_neg_one_iff: "- numeral n = - 1 \<longleftrightarrow> n = One"
  using neg_numeral_eq_iff [of n One] by (auto simp add: numeral_One)

lemma neg_one_neq_zero: "- 1 \<noteq> 0"
  by simp

lemma zero_neq_neg_one: "0 \<noteq> - 1"
  by simp

lemma neg_one_neq_one: "- 1 \<noteq> 1"
  using neg_numeral_neq_numeral [of One One] by (simp only: numeral_One not_False_eq_True)

lemma one_neq_neg_one: "1 \<noteq> - 1"
  using numeral_neq_neg_numeral [of One One] by (simp only: numeral_One not_False_eq_True)

lemmas eq_neg_numeral_simps [simp] =
  neg_numeral_eq_iff
  numeral_neq_neg_numeral neg_numeral_neq_numeral
  one_neq_neg_numeral neg_numeral_neq_one
  zero_neq_neg_numeral neg_numeral_neq_zero
  neg_one_neq_numeral numeral_neq_neg_one
  neg_one_eq_numeral_iff numeral_eq_neg_one_iff
  neg_one_neq_zero zero_neq_neg_one
  neg_one_neq_one one_neq_neg_one

end

subsubsection \<open>Structures with negation and order: class \<open>linordered_idom\<close>\<close>

context linordered_idom
begin

subclass ring_char_0 ..

lemma neg_numeral_le_iff: "- numeral m \<le> - numeral n \<longleftrightarrow> n \<le> m"
  by (simp only: neg_le_iff_le numeral_le_iff)

lemma neg_numeral_less_iff: "- numeral m < - numeral n \<longleftrightarrow> n < m"
  by (simp only: neg_less_iff_less numeral_less_iff)

lemma neg_numeral_less_zero: "- numeral n < 0"
  by (simp only: neg_less_0_iff_less zero_less_numeral)

lemma neg_numeral_le_zero: "- numeral n \<le> 0"
  by (simp only: neg_le_0_iff_le zero_le_numeral)

lemma not_zero_less_neg_numeral: "\<not> 0 < - numeral n"
  by (simp only: not_less neg_numeral_le_zero)

lemma not_zero_le_neg_numeral: "\<not> 0 \<le> - numeral n"
  by (simp only: not_le neg_numeral_less_zero)

lemma neg_numeral_less_numeral: "- numeral m < numeral n"
  using neg_numeral_less_zero zero_less_numeral by (rule less_trans)

lemma neg_numeral_le_numeral: "- numeral m \<le> numeral n"
  by (simp only: less_imp_le neg_numeral_less_numeral)

lemma not_numeral_less_neg_numeral: "\<not> numeral m < - numeral n"
  by (simp only: not_less neg_numeral_le_numeral)

lemma not_numeral_le_neg_numeral: "\<not> numeral m \<le> - numeral n"
  by (simp only: not_le neg_numeral_less_numeral)

lemma neg_numeral_less_one: "- numeral m < 1"
  by (rule neg_numeral_less_numeral [of m One, unfolded numeral_One])

lemma neg_numeral_le_one: "- numeral m \<le> 1"
  by (rule neg_numeral_le_numeral [of m One, unfolded numeral_One])

lemma not_one_less_neg_numeral: "\<not> 1 < - numeral m"
  by (simp only: not_less neg_numeral_le_one)

lemma not_one_le_neg_numeral: "\<not> 1 \<le> - numeral m"
  by (simp only: not_le neg_numeral_less_one)

lemma not_numeral_less_neg_one: "\<not> numeral m < - 1"
  using not_numeral_less_neg_numeral [of m One] by (simp add: numeral_One)

lemma not_numeral_le_neg_one: "\<not> numeral m \<le> - 1"
  using not_numeral_le_neg_numeral [of m One] by (simp add: numeral_One)

lemma neg_one_less_numeral: "- 1 < numeral m"
  using neg_numeral_less_numeral [of One m] by (simp add: numeral_One)

lemma neg_one_le_numeral: "- 1 \<le> numeral m"
  using neg_numeral_le_numeral [of One m] by (simp add: numeral_One)

lemma neg_numeral_less_neg_one_iff: "- numeral m < - 1 \<longleftrightarrow> m \<noteq> One"
  by (cases m) simp_all

lemma neg_numeral_le_neg_one: "- numeral m \<le> - 1"
  by simp

lemma not_neg_one_less_neg_numeral: "\<not> - 1 < - numeral m"
  by simp

lemma not_neg_one_le_neg_numeral_iff: "\<not> - 1 \<le> - numeral m \<longleftrightarrow> m \<noteq> One"
  by (cases m) simp_all

lemma sub_non_negative: "sub n m \<ge> 0 \<longleftrightarrow> n \<ge> m"
  by (simp only: sub_def le_diff_eq) simp

lemma sub_positive: "sub n m > 0 \<longleftrightarrow> n > m"
  by (simp only: sub_def less_diff_eq) simp

lemma sub_non_positive: "sub n m \<le> 0 \<longleftrightarrow> n \<le> m"
  by (simp only: sub_def diff_le_eq) simp

lemma sub_negative: "sub n m < 0 \<longleftrightarrow> n < m"
  by (simp only: sub_def diff_less_eq) simp

lemmas le_neg_numeral_simps [simp] =
  neg_numeral_le_iff
  neg_numeral_le_numeral not_numeral_le_neg_numeral
  neg_numeral_le_zero not_zero_le_neg_numeral
  neg_numeral_le_one not_one_le_neg_numeral
  neg_one_le_numeral not_numeral_le_neg_one
  neg_numeral_le_neg_one not_neg_one_le_neg_numeral_iff

lemma le_minus_one_simps [simp]:
  "- 1 \<le> 0"
  "- 1 \<le> 1"
  "\<not> 0 \<le> - 1"
  "\<not> 1 \<le> - 1"
  by simp_all

lemmas less_neg_numeral_simps [simp] =
  neg_numeral_less_iff
  neg_numeral_less_numeral not_numeral_less_neg_numeral
  neg_numeral_less_zero not_zero_less_neg_numeral
  neg_numeral_less_one not_one_less_neg_numeral
  neg_one_less_numeral not_numeral_less_neg_one
  neg_numeral_less_neg_one_iff not_neg_one_less_neg_numeral

lemma less_minus_one_simps [simp]:
  "- 1 < 0"
  "- 1 < 1"
  "\<not> 0 < - 1"
  "\<not> 1 < - 1"
  by (simp_all add: less_le)

lemma abs_numeral [simp]: "\<bar>numeral n\<bar> = numeral n"
  by simp

lemma abs_neg_numeral [simp]: "\<bar>- numeral n\<bar> = numeral n"
  by (simp only: abs_minus_cancel abs_numeral)

lemma abs_neg_one [simp]: "\<bar>- 1\<bar> = 1"
  by simp

end

subsubsection \<open>Natural numbers\<close>

lemma Suc_1 [simp]: "Suc 1 = 2"
  unfolding Suc_eq_plus1 by (rule one_add_one)

lemma Suc_numeral [simp]: "Suc (numeral n) = numeral (n + One)"
  unfolding Suc_eq_plus1 by (rule numeral_plus_one)

definition pred_numeral :: "num \<Rightarrow> nat"
  where [code del]: "pred_numeral k = numeral k - 1"

lemma numeral_eq_Suc: "numeral k = Suc (pred_numeral k)"
  by (simp add: pred_numeral_def)

lemma eval_nat_numeral:
  "numeral One = Suc 0"
  "numeral (Bit0 n) = Suc (numeral (BitM n))"
  "numeral (Bit1 n) = Suc (numeral (Bit0 n))"
  by (simp_all add: numeral.simps BitM_plus_one)

lemma pred_numeral_simps [simp]:
  "pred_numeral One = 0"
  "pred_numeral (Bit0 k) = numeral (BitM k)"
  "pred_numeral (Bit1 k) = numeral (Bit0 k)"
  by (simp_all only: pred_numeral_def eval_nat_numeral diff_Suc_Suc diff_0)

lemma numeral_2_eq_2: "2 = Suc (Suc 0)"
  by (simp add: eval_nat_numeral)

lemma numeral_3_eq_3: "3 = Suc (Suc (Suc 0))"
  by (simp add: eval_nat_numeral)

lemma numeral_1_eq_Suc_0: "Numeral1 = Suc 0"
  by (simp only: numeral_One One_nat_def)

lemma Suc_nat_number_of_add: "Suc (numeral v + n) = numeral (v + One) + n"
  by simp

lemma numerals: "Numeral1 = (1::nat)" "2 = Suc (Suc 0)"
  by (rule numeral_One) (rule numeral_2_eq_2)

lemmas numeral_nat = eval_nat_numeral BitM.simps One_nat_def

text \<open>Comparisons involving @{term Suc}.\<close>

lemma eq_numeral_Suc [simp]: "numeral k = Suc n \<longleftrightarrow> pred_numeral k = n"
  by (simp add: numeral_eq_Suc)

lemma Suc_eq_numeral [simp]: "Suc n = numeral k \<longleftrightarrow> n = pred_numeral k"
  by (simp add: numeral_eq_Suc)

lemma less_numeral_Suc [simp]: "numeral k < Suc n \<longleftrightarrow> pred_numeral k < n"
  by (simp add: numeral_eq_Suc)

lemma less_Suc_numeral [simp]: "Suc n < numeral k \<longleftrightarrow> n < pred_numeral k"
  by (simp add: numeral_eq_Suc)

lemma le_numeral_Suc [simp]: "numeral k \<le> Suc n \<longleftrightarrow> pred_numeral k \<le> n"
  by (simp add: numeral_eq_Suc)

lemma le_Suc_numeral [simp]: "Suc n \<le> numeral k \<longleftrightarrow> n \<le> pred_numeral k"
  by (simp add: numeral_eq_Suc)

lemma diff_Suc_numeral [simp]: "Suc n - numeral k = n - pred_numeral k"
  by (simp add: numeral_eq_Suc)

lemma diff_numeral_Suc [simp]: "numeral k - Suc n = pred_numeral k - n"
  by (simp add: numeral_eq_Suc)

lemma max_Suc_numeral [simp]: "max (Suc n) (numeral k) = Suc (max n (pred_numeral k))"
  by (simp add: numeral_eq_Suc)

lemma max_numeral_Suc [simp]: "max (numeral k) (Suc n) = Suc (max (pred_numeral k) n)"
  by (simp add: numeral_eq_Suc)

lemma min_Suc_numeral [simp]: "min (Suc n) (numeral k) = Suc (min n (pred_numeral k))"
  by (simp add: numeral_eq_Suc)

lemma min_numeral_Suc [simp]: "min (numeral k) (Suc n) = Suc (min (pred_numeral k) n)"
  by (simp add: numeral_eq_Suc)

text \<open>For @{term case_nat} and @{term rec_nat}.\<close>

lemma case_nat_numeral [simp]: "case_nat a f (numeral v) = (let pv = pred_numeral v in f pv)"
  by (simp add: numeral_eq_Suc)

lemma case_nat_add_eq_if [simp]:
  "case_nat a f ((numeral v) + n) = (let pv = pred_numeral v in f (pv + n))"
  by (simp add: numeral_eq_Suc)

lemma rec_nat_numeral [simp]:
  "rec_nat a f (numeral v) = (let pv = pred_numeral v in f pv (rec_nat a f pv))"
  by (simp add: numeral_eq_Suc Let_def)

lemma rec_nat_add_eq_if [simp]:
  "rec_nat a f (numeral v + n) = (let pv = pred_numeral v in f (pv + n) (rec_nat a f (pv + n)))"
  by (simp add: numeral_eq_Suc Let_def)

text \<open>Case analysis on @{term "n < 2"}.\<close>
lemma less_2_cases: "n < 2 \<Longrightarrow> n = 0 \<or> n = Suc 0"
  by (auto simp add: numeral_2_eq_2)

text \<open>Removal of Small Numerals: 0, 1 and (in additive positions) 2.\<close>
text \<open>bh: Are these rules really a good idea?\<close>

lemma add_2_eq_Suc [simp]: "2 + n = Suc (Suc n)"
  by simp

lemma add_2_eq_Suc' [simp]: "n + 2 = Suc (Suc n)"
  by simp

text \<open>Can be used to eliminate long strings of Sucs, but not by default.\<close>
lemma Suc3_eq_add_3: "Suc (Suc (Suc n)) = 3 + n"
  by simp

lemmas nat_1_add_1 = one_add_one [where 'a=nat] (* legacy *)

subsection \<open>Particular lemmas concerning @{term 2}\<close>

context linordered_field
begin

subclass field_char_0 ..

lemma half_gt_zero_iff: "0 < a / 2 \<longleftrightarrow> 0 < a"
  by (auto simp add: field_simps)

lemma half_gt_zero [simp]: "0 < a \<Longrightarrow> 0 < a / 2"
  by (simp add: half_gt_zero_iff)

end

subsection \<open>Numeral equations as default simplification rules\<close>

declare (in numeral) numeral_One [simp]
declare (in numeral) numeral_plus_numeral [simp]
declare (in numeral) add_numeral_special [simp]
declare (in neg_numeral) add_neg_numeral_simps [simp]
declare (in neg_numeral) add_neg_numeral_special [simp]
declare (in neg_numeral) diff_numeral_simps [simp]
declare (in neg_numeral) diff_numeral_special [simp]
declare (in semiring_numeral) numeral_times_numeral [simp]
declare (in ring_1) mult_neg_numeral_simps [simp]

subsection \<open>Setting up simprocs\<close>

lemma mult_numeral_1: "Numeral1 * a = a"
  for a :: "'a::semiring_numeral"
  by simp

lemma mult_numeral_1_right: "a * Numeral1 = a"
  for a :: "'a::semiring_numeral"
  by simp

lemma divide_numeral_1: "a / Numeral1 = a"
  for a :: "'a::field"
  by simp

lemma inverse_numeral_1: "inverse Numeral1 = (Numeral1::'a::division_ring)"
  by simp

text \<open>
  Theorem lists for the cancellation simprocs. The use of a binary
  numeral for 1 reduces the number of special cases.
\<close>

lemma mult_1s:
  "Numeral1 * a = a"
  "a * Numeral1 = a"
  "- Numeral1 * b = - b"
  "b * - Numeral1 = - b"
  for a :: "'a::semiring_numeral" and b :: "'b::ring_1"
  by simp_all

setup \<open>
  Reorient_Proc.add
    (fn Const (@{const_name numeral}, _) $ _ => true
      | Const (@{const_name uminus}, _) $ (Const (@{const_name numeral}, _) $ _) => true
      | _ => false)
\<close>

simproc_setup reorient_numeral ("numeral w = x" | "- numeral w = y") =
  Reorient_Proc.proc

subsubsection \<open>Simplification of arithmetic operations on integer constants\<close>

lemmas arith_special = (* already declared simp above *)
  add_numeral_special add_neg_numeral_special
  diff_numeral_special

lemmas arith_extra_simps = (* rules already in simpset *)
  numeral_plus_numeral add_neg_numeral_simps add_0_left add_0_right
  minus_zero
  diff_numeral_simps diff_0 diff_0_right
  numeral_times_numeral mult_neg_numeral_simps
  mult_zero_left mult_zero_right
  abs_numeral abs_neg_numeral

text \<open>
  For making a minimal simpset, one must include these default simprules.
  Also include \<open>simp_thms\<close>.
\<close>

lemmas arith_simps =
  add_num_simps mult_num_simps sub_num_simps
  BitM.simps dbl_simps dbl_inc_simps dbl_dec_simps
  abs_zero abs_one arith_extra_simps

lemmas more_arith_simps =
  neg_le_iff_le
  minus_zero left_minus right_minus
  mult_1_left mult_1_right
  mult_minus_left mult_minus_right
  minus_add_distrib minus_minus mult.assoc

lemmas of_nat_simps =
  of_nat_0 of_nat_1 of_nat_Suc of_nat_add of_nat_mult

text \<open>Simplification of relational operations.\<close>

lemmas eq_numeral_extra =
  zero_neq_one one_neq_zero

lemmas rel_simps =
  le_num_simps less_num_simps eq_num_simps
  le_numeral_simps le_neg_numeral_simps le_minus_one_simps le_numeral_extra
  less_numeral_simps less_neg_numeral_simps less_minus_one_simps less_numeral_extra
  eq_numeral_simps eq_neg_numeral_simps eq_numeral_extra

lemma Let_numeral [simp]: "Let (numeral v) f = f (numeral v)"
  \<comment> \<open>Unfold all \<open>let\<close>s involving constants\<close>
  unfolding Let_def ..

lemma Let_neg_numeral [simp]: "Let (- numeral v) f = f (- numeral v)"
  \<comment> \<open>Unfold all \<open>let\<close>s involving constants\<close>
  unfolding Let_def ..

declaration \<open>
let
  fun number_of ctxt T n =
    if not (Sign.of_sort (Proof_Context.theory_of ctxt) (T, @{sort numeral}))
    then raise CTERM ("number_of", [])
    else Numeral.mk_cnumber (Thm.ctyp_of ctxt T) n;
in
  K (
    Lin_Arith.add_simps
      @{thms arith_simps more_arith_simps rel_simps pred_numeral_simps
        arith_special numeral_One of_nat_simps uminus_numeral_One}
    #> Lin_Arith.add_simps
      @{thms Suc_numeral Let_numeral Let_neg_numeral Let_0 Let_1
        le_Suc_numeral le_numeral_Suc less_Suc_numeral less_numeral_Suc
        Suc_eq_numeral eq_numeral_Suc mult_Suc mult_Suc_right of_nat_numeral}
    #> Lin_Arith.set_number_of number_of)
end
\<close>

subsubsection \<open>Simplification of arithmetic when nested to the right\<close>

lemma add_numeral_left [simp]: "numeral v + (numeral w + z) = (numeral(v + w) + z)"
  by (simp_all add: add.assoc [symmetric])

lemma add_neg_numeral_left [simp]:
  "numeral v + (- numeral w + y) = (sub v w + y)"
  "- numeral v + (numeral w + y) = (sub w v + y)"
  "- numeral v + (- numeral w + y) = (- numeral(v + w) + y)"
  by (simp_all add: add.assoc [symmetric])

lemma mult_numeral_left [simp]:
  "numeral v * (numeral w * z) = (numeral(v * w) * z :: 'a::semiring_numeral)"
  "- numeral v * (numeral w * y) = (- numeral(v * w) * y :: 'b::ring_1)"
  "numeral v * (- numeral w * y) = (- numeral(v * w) * y :: 'b::ring_1)"
  "- numeral v * (- numeral w * y) = (numeral(v * w) * y :: 'b::ring_1)"
  by (simp_all add: mult.assoc [symmetric])

hide_const (open) One Bit0 Bit1 BitM inc pow sqr sub dbl dbl_inc dbl_dec

subsection \<open>Code module namespace\<close>

code_identifier
  code_module Num \<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith

end


theory Ex211
imports Main List
begin

datatype exp = Var | Const int | Add exp exp | Mult exp exp

fun eval :: "exp \<Rightarrow> int \<Rightarrow> int" where
"eval Var x = x" |
"eval (Const n) x = n" |
"eval (Add e1 e2) x = (eval e1 x) + (eval e2 x)" |
"eval (Mult e1 e2) x = (eval e1 x) * (eval e2 x)"

value "eval (Add Var (Const 2)) 1"

fun evalp :: "int list \<Rightarrow> int \<Rightarrow> int" where
"evalp [] x = 0" |
"evalp (y#ys) x = y + ((evalp ys x) * x)"

value "evalp [4,2,-1,3] 0"
value "evalp [4,2,-1,3] 1"
value "evalp [4,2,-1,3] (-1)"
value "evalp [4,2,-1,3] 2"
value "evalp [4*2,2*2,-1*2,3*2] 1"
value "evalp [4*3,2*3,-1*3,3*3] 1"
value "evalp [4*2,2*2,-1*2,3*2] 2"

fun add_pair :: "(int * int) \<Rightarrow> int" where
"add_pair (x, y) = x + y"

value "add_pair (1, 2)"

fun pad_zip :: "int list \<Rightarrow> int list \<Rightarrow> (int * int) list" where
"pad_zip [] [] = []" |
"pad_zip (x#xs) [] = (x, 0) # pad_zip xs []" |
"pad_zip [] (y#ys) = (0, y) # pad_zip [] ys" |
"pad_zip (x#xs) (y#ys) = (x, y) # pad_zip xs ys"

fun add_list :: "int list \<Rightarrow> int list \<Rightarrow> int list" where
"add_list xs ys = map add_pair (pad_zip xs ys)"

value "add_list [1, 2] [3, 4, 5]"

fun merge :: "int list \<Rightarrow> int list \<Rightarrow> int list" where
"merge [] ys = []" |
"merge (x#xs) ys = add_list [ x * y. y <- ys ] (0 # (merge xs ys))"

value "merge [1, 3] [2, 1]"

fun coeffs :: "exp \<Rightarrow> int list" where
"coeffs Var = [0, 1]" |
"coeffs (Const n) = [n]" |
"coeffs (Add e1 e2) = add_list (coeffs e1) (coeffs e2)" |
"coeffs (Mult e1 e2) = merge (coeffs e1) (coeffs e2)"

value "coeffs (Const 1)"
value "coeffs (Const 2)"
value "coeffs (Add (Const 1) (Const 2))"
value "coeffs (Mult (Const 1) (Const 2))"
value "coeffs (Mult (Const 2) Var)"
value "coeffs (Mult (Const 2) (Add (Const 2) Var))"
value "coeffs Var"
value "coeffs (Add (Const 2) Var)"
value "coeffs (Mult Var (Add (Const 2) Var))"
value "coeffs (Mult (Add (Const 3) (Mult (Const 2) Var)) (Add (Const 2) Var))"

lemma [simp]:"evalp (map (op * a) ys) x = a * evalp ys x"
apply(induction ys)
apply(auto simp add:algebra_simps)
done

lemma [simp]:"evalp (merge xs ys) x = (evalp xs x) * (evalp ys x)"
apply(induction xs)
apply(auto simp add:algebra_simps)
done

lemma "evalp (coeffs e) x = eval e x"
apply(induction e)
apply(auto)
done

end


theory Arith3_1
imports Main
begin

primrec pow :: "nat \<Rightarrow> nat \<Rightarrow> nat"
where
  "pow x 0 = 1"
| "pow x (Suc n) = x * (pow x n)"

lemma pow_add: "pow x (m + n) = pow x m * pow x n"
  apply (induct m)
  apply auto
done

theorem "pow (pow x m) n = pow x (m * n)"
  apply (induct n arbitrary:m)
  apply (simp add:pow_add)+
done

primrec sum :: "nat list \<Rightarrow> nat"
where
  "sum [] = 0"
| "sum (x#xs) = x + sum xs"

lemma sum_append: "sum (xs @ ys) = sum xs + sum ys"
  apply (induct xs)
  apply auto
done

theorem "sum (rev xs) = sum xs"
  apply (induct xs)
  apply simp
  apply (simp add:sum_append)
done

fun Sum :: "(nat \<Rightarrow> nat) \<Rightarrow> nat  \<Rightarrow> nat"
where
  "Sum f 0 = 0"
| "Sum f (Suc n) = f n + Sum f n"

theorem "Sum (\<lambda> i. f i + g i) n = Sum f n + Sum g n"
  apply (induct n)
  apply simp+
done

value "Sum (\<lambda>x. x) 0"
value "Sum (\<lambda>x. x) 4"

theorem "Sum f (k + l) = Sum f k + Sum (\<lambda> i. f (k + i))  l"
  apply (induct l)
  apply simp+
done

value "map (\<lambda>x. x) [1,2]"

theorem "Sum f n = sum (map f [0..<n])"
  apply (induct n)
  apply (simp add:sum_append)+
done

end


theory Prog_Prove_3_2
  imports Main
begin

datatype 'a tree = Tip | Node "'a tree" 'a " 'a tree"

fun set :: "'a tree \<Rightarrow> 'a set" where
"set Tip = {}" |
"set (Node xt a yt) = set xt \<union> ({a} \<union> set yt)"

(* make function get int option *)
fun get_max_opt :: "int option \<Rightarrow> int option \<Rightarrow> int option" where
"get_max_opt None None = None" |
"get_max_opt (Some a) None = Some a" |
"get_max_opt None (Some a) = Some a" |
"get_max_opt (Some a) (Some b) = Some(max a b)"

fun get_min_opt :: "int option \<Rightarrow> int option \<Rightarrow> int option" where
"get_min_opt None None = None" |
"get_min_opt (Some a) None = Some a" |
"get_min_opt None (Some a) = Some a" |
"get_min_opt (Some a) (Some b) = Some(min a b)"

(* make function int less than int option *)
fun option_is_less_than_int :: "int option \<Rightarrow> int \<Rightarrow> bool" where
"option_is_less_than_int None b = True" |
"option_is_less_than_int (Some a) b = (a \<le> b)"

fun option_is_greater_than_int :: "int option \<Rightarrow> int \<Rightarrow> bool" where
"option_is_greater_than_int None b = True" |
"option_is_greater_than_int (Some a) b = (a \<ge> b)"

fun get_min_opt_from_tree :: "int tree \<Rightarrow> int option" where
"get_min_opt_from_tree Tip = None" |
"get_min_opt_from_tree (Node xt a yt) =
    get_min_opt (Some a) (get_min_opt (get_min_opt_from_tree xt) (get_min_opt_from_tree yt))"

fun get_max_opt_from_tree :: "int tree \<Rightarrow> int option" where
"get_max_opt_from_tree Tip = None" |
"get_max_opt_from_tree (Node xt a yt) =
    get_max_opt (Some a) (get_max_opt (get_max_opt_from_tree xt) (get_max_opt_from_tree yt))  "

fun ord :: "int tree \<Rightarrow> bool" where
"ord Tip = True" |
"ord (Node xt a yt) = ((option_is_less_than_int (get_max_opt_from_tree xt) a) \<and> (option_is_greater_than_int (get_min_opt_from_tree yt) a) \<and> (ord xt) \<and> (ord yt))"

fun ins :: "int \<Rightarrow> int tree \<Rightarrow> int tree" where
"ins a Tip = Node Tip a Tip" |
"ins a (Node xt b yt) = (if (a = b) then (Node xt b yt) else
                        (if (a < b) then (Node (ins a xt) b yt) else
                        (Node xt b (ins a yt)) ))"

theorem "set (ins x t) = {x} \<union> set t"
  apply(induction t)
   apply(auto)
  done

lemma get_max_opt_com_1 : "get_max_opt (Some a) y = get_max_opt y (Some a)"
  apply(induction y)
   apply(auto)
  done

lemma get_max_opt_com_2 : "get_max_opt (get_max_opt x (Some a)) y =
  get_max_opt x (get_max_opt y (Some a))"
  apply(induction x; induction y)
     apply(auto)
  done

lemma get_max_opt_com_3 : "get_max_opt (get_max_opt x y) z =
 get_max_opt x (get_max_opt y z)"
  apply(induction x; induction y; induction z)
         apply(auto)
  done

lemma simplify_max_inserted_tree:
"get_max_opt_from_tree (ins i t1) =
  get_max_opt (Some i) (get_max_opt_from_tree t1)"
  apply(induction t1)
   apply(auto simp add:get_max_opt_com_1)
    apply(auto simp add:get_max_opt_com_2)
   apply(auto simp add:get_max_opt_com_3)
  done

lemma get_min_opt_com_1 : "get_min_opt (Some a) y = get_min_opt y (Some a)"
  apply(induction y)
   apply(auto)
  done

lemma get_min_opt_com_2 : "get_min_opt (get_min_opt x (Some a)) y =
  get_min_opt x (get_min_opt y (Some a))"
  apply(induction x; induction y)
     apply(auto)
  done

lemma get_min_opt_com_3 : "get_min_opt (get_min_opt x y) z =
 get_min_opt x (get_min_opt y z)"
  apply(induction x; induction y; induction z)
         apply(auto)
  done

lemma simplify_min_inserted_tree:
"get_min_opt_from_tree (ins i t1) =
  get_min_opt (Some i) (get_min_opt_from_tree t1)"
  apply(induction t1)
   apply(auto simp add:get_min_opt_com_1)
    apply(auto simp add:get_min_opt_com_2)
   apply(auto simp add:get_min_opt_com_3)
  done

lemma less_than_max_opt:
    "option_is_less_than_int t1 x2 \<Longrightarrow>
       option_is_less_than_int t2 x2 \<Longrightarrow>
          option_is_less_than_int (get_max_opt t1 t2) x2"
  apply(induction t1; induction t2)
   apply(auto)
  done

lemma greater_than_min_opt:
    "option_is_greater_than_int t1 x2 \<Longrightarrow>
       option_is_greater_than_int t2 x2 \<Longrightarrow>
          option_is_greater_than_int (get_min_opt t1 t2) x2"
  apply(induction t1; induction t2)
   apply(auto)
  done

theorem "ord t \<Longrightarrow> ord (ins i t)"
  apply(induction t)

   apply(auto simp add:simplify_max_inserted_tree)
   apply(auto simp add:less_than_max_opt)
   apply(auto simp add:simplify_min_inserted_tree)
   apply(auto simp add:greater_than_min_opt)

  done
end


theory Counting imports Main begin

section "https://principia.connpass.com/event/182988/"
subsection "Q1"

fun count_pos :: "int list \<Rightarrow> nat" where
  count_pos_Nil: "count_pos [] = 0" |
  count_pos_Cons: "count_pos (x#xs) = (if x > 0 then Suc (count_pos xs) else count_pos xs)"

lemma count_pos_append: "count_pos (xs@ys) = (count_pos xs) + (count_pos ys)"
  apply(induct xs)
  apply(auto)
  done

subsection "Q2"

lemma Collect_cong_UnR: "(\<And>i. P i = (R i \<or> Q i)) \<Longrightarrow> {i. P i} = {i. R i} \<union> {i. Q i}"
  apply(auto)
  done

lemma lt_Suc_iff: "(i < Suc n) = (i < n \<or> i = n)"
  apply(auto)
  done

lemma nth_append_iff: "(i < length xs \<and> P ((xs @ [x]) ! i)) = (i < length xs \<and> P (xs!i))"
  apply(subst nth_append)
  apply(auto)
  done

lemma nth_append_iff_UnR: "{i. i < length (xs@[x]) \<and> P ((xs@[x])!i) }
     = {i. i < length xs \<and> P (xs!i) } \<union> { i. i = length xs \<and> P x }" for P::"'a \<Rightarrow> bool"
  apply(rule Collect_cong_UnR)
  apply(simp)
  apply(subst lt_Suc_iff)
  apply(subst conj_disj_distribR)
  apply(subst nth_append_iff)
  apply(subst nth_append)
  apply(auto)
  done

lemma idx_set_disjoint: "{i. i < length xs \<and> 0 < xs ! i} \<inter> {i. i = length xs \<and> 0 < x} = {}"
  apply(auto)
  done

lemma ab_cd_eq_a_cdb: "a + b = c + d \<Longrightarrow> a = c + d - b" for a::nat and b::nat and c::nat and d::nat
  apply(auto)
  done

lemma card_Un_iff: "\<lbrakk> finite A; finite B \<rbrakk> \<Longrightarrow> card (A \<union> B) = card A + card B - card (A \<inter> B)"
  apply(rule ab_cd_eq_a_cdb)
  apply(rule sym)
  apply(erule card_Un_Int)
  apply(assumption)
  done

theorem "card {i. i < length xs \<and> xs ! i > 0} = count_pos xs"
  apply(rule rev_induct)
  apply(simp)
  apply(subst nth_append_iff_UnR)
  apply(subst card_Un_iff)
  apply(simp)
  apply(simp)
  apply(subst idx_set_disjoint)
  apply(simp)
  apply(subst count_pos_append)
  apply(subst count_pos_Cons)
  apply(case_tac "0 < x")
  apply(simp)
  apply(simp)
  done
end


theory Chapter4
  imports Main Chapter3_2
begin

datatype 'a tree = Tip | Node "'a tree" 'a "'a tree"

fun set::"'a tree \<Rightarrow> 'a set" where
"set Tip = {}" |
"set (tree.Node l a r) = (set l) \<union> {a} \<union> (set r)"

fun ord::"int tree \<Rightarrow> bool" where
"ord Tip = True" |
"ord (Node l a r) = ((ord l) \<and> (ord r) \<and> (\<forall>x \<in> (set l).x < a) \<and> (\<forall>x \<in> (set r). x > a))"

fun ins::"int \<Rightarrow> (int tree) \<Rightarrow> (int tree)" where
"ins n Tip = Node Tip n Tip" |
"ins n (Node l a r) = (if (n < a) then Node (ins n l) a r
                      else if (n > a) then Node l a (ins n r)
                      else Node l a r)"

theorem ins_union [simp]: "set (ins x t) = {x} \<union> set t"
  apply (induction t)
  apply (auto)
  done

theorem ins_preserves_ord [simp]: "(ord t) \<Longrightarrow> ord (ins i t)"
  apply (induction t)
  apply (auto split: if_splits)
  done

inductive palindrome::"'a list \<Rightarrow> bool" where
pal_base1: "palindrome []" |
pal_base: "palindrome [x]" |
pal_step: "palindrome xs \<Longrightarrow> palindrome (x#(xs@[x]))"

inductive star::"('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r where
refl: "star r x x" |
step: "r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z"

lemma star_trans: "star r x y \<Longrightarrow> star r y z \<Longrightarrow> star r x z"
  apply (induction rule: star.induct)
   apply (assumption)
  apply (metis step)
  done

theorem rev_preserves_palindrome: "palindrome xs \<Longrightarrow> (rev xs = xs)"
  apply (induction xs rule: palindrome.induct)
  apply (simp_all)
  done

inductive star':: "('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> 'a \<Rightarrow> 'a \<Rightarrow> bool" for r where
refl': "star' r x x" |
step': "star' r x y \<Longrightarrow> r y z \<Longrightarrow> star' r x z"

lemma star'_alt_def:"star' r y z \<Longrightarrow> r x y \<Longrightarrow> star' r x z"
  apply (induction rule: star'.induct)
   apply (auto intro: refl' step')
  done

lemma star_impl_star' [simp]: "star r x y \<Longrightarrow> star' r x y"
  apply (induction rule: star.induct)
   apply (simp add: refl')
  apply (auto intro: star'_alt_def)
  done

lemma star_alt_def: "star r x y \<Longrightarrow> r y z \<Longrightarrow> star r x z"
  apply (induction arbitrary: z rule: star.induct)
   apply (simp add: refl step)
  apply (metis step)
  done

lemma star'_impl_star [simp, intro]: "star' r x y \<Longrightarrow> star r x y"
  apply (induction rule: star'.induct)
   apply (simp add: refl)
  apply (auto intro: star_alt_def)
  done

inductive iter::"('a \<Rightarrow> 'a \<Rightarrow> bool) \<Rightarrow> nat \<Rightarrow> 'a  \<Rightarrow> 'a \<Rightarrow> bool" for r where
iter0: "iter r 0 x x" |
iterS: "r x z \<Longrightarrow> iter r n z y \<Longrightarrow> iter r (Suc n) x y"

datatype alpha = a | b

inductive S::"alpha list \<Rightarrow> bool" where
S0: "S Nil" |
S1: "S w \<Longrightarrow> S (a # (w @ [b]))" |
S2: "S w1 \<Longrightarrow> S w2 \<Longrightarrow> S (w1 @ w2)"

inductive T::"alpha list \<Rightarrow> bool" where
T0: "T Nil" |
T1: "T w1 \<Longrightarrow> T w2 \<Longrightarrow> T (w1 @ [a] @ w2 @ [b])"

lemma T_imp_S: "T w \<Longrightarrow> S w"
  apply (induction rule: T.induct)
   apply (rule S0)
  apply (rule)
  apply (auto intro: S1)
  done
(*TODO: find out more about metis*)
lemma idk: "T w2 \<Longrightarrow> T w1 \<Longrightarrow> T (w1 @ w2)"
  apply (induction rule: T.induct)
  apply (simp)
  apply (metis T1 append_assoc)
  done

lemma S_imp_T: "S w \<Longrightarrow> T w"
  apply (induction rule: S.induct)
    apply (rule T0)
   apply (metis T0 T1 append_Cons append_Nil)
  apply (auto simp add: idk)
  done

theorem S_eq_T: "S w = T w"
  apply (auto simp add: S_imp_T T_imp_S)
  done

inductive aval_rel::"aexp \<Rightarrow> state \<Rightarrow> val \<Rightarrow> bool" where
a_n: "aval_rel (N n) s n" |
a_v: "aval_rel (V x) s (s x)" |
a_p: "aval_rel a1 s v1 \<Longrightarrow> aval_rel a2 s v2 \<Longrightarrow> aval_rel (Plus a1 a2) s (v1 + v2)" |
a_t: "aval_rel a1 s v1 \<Longrightarrow> aval_rel a2 s v2 \<Longrightarrow> aval_rel (Times a1 a2) s (v1 * v2)"

lemma aval_rel_imp_aval: "aval_rel a1 s v \<Longrightarrow> aval a1 s = v"
  apply (induction rule: aval_rel.induct)
  apply (auto)
  done

lemma aval_imp_aval_rel: "aval a1 s = v \<Longrightarrow> aval_rel a1 s v"
  apply (induction a1 arbitrary: v)
    apply (auto intro: a_n a_v a_p a_t)
  done

theorem aval_eq_aval_rel: "aval a1 s = v \<longleftrightarrow> aval_rel a1 s v"
  apply (auto simp add: aval_imp_aval_rel intro: aval_rel_imp_aval)
  done

inductive ok::"nat \<Rightarrow> instr list \<Rightarrow> nat \<Rightarrow> bool" where
ok_nil: "ok n [] n" |
ok_li: "ok (Suc n) l n' \<Longrightarrow> ok n ((LOADI _)#l) n'" |
ok_l: "ok (Suc n) l n' \<Longrightarrow> ok n ((LOAD _)#l) n'" |
ok_a: "ok n l n' \<Longrightarrow> n \<ge> 1 \<Longrightarrow> ok (Suc n) ((instr.ADD)#l) n'" |
ok_t: "ok n l n' \<Longrightarrow> n \<ge> 1 \<Longrightarrow> ok (Suc n) ((TIMES)#l) n'"

fun exec1::"instr \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where
"exec1 (LOADI n) _ stk = (n # stk)" |
"exec1 (LOAD x) s stk = ((s x) # stk)" |
"exec1 instr.ADD _ stk = ((hd stk + hd2 stk) # (tl2 stk))" |
"exec1 TIMES _ stk = ((hd stk * hd2 stk) # (tl2 stk))"

fun exec::"instr list \<Rightarrow> state \<Rightarrow> stack \<Rightarrow> stack" where
"exec Nil _ stk = stk" |
"exec (i#is) s stk = (exec is s (exec1 i s stk))"

lemma "\<lbrakk>ok n is n'; length stk = n\<rbrakk> \<Longrightarrow> length (exec is s stk) = n'"
  apply (induction arbitrary: stk rule: ok.induct)
  apply (auto intro: ok_nil ok_l ok_li ok_a ok_t)
  done

end