theory MinWeightBasis
  imports "NREST.NREST" "SeprefTime.Refine_Foreach"
    "List-Index.List_Index" Matroids.Matroid
begin

abbreviation "sorted_wrt_w w == sorted_wrt (\<lambda>e1 e2. w e1 \<le> w e2)"

locale minWeightBasis = matroid carrier indep for carrier::"'a set" and indep  +
  fixes w :: "'a \<Rightarrow> 'b::{linorder, ordered_comm_monoid_add}"
begin

section \<open>minWeightBasis algorithm\<close>

subsection \<open>Proof that it computes an minimum Basis\<close>

definition minBasis where "minBasis B \<equiv> basis B \<and> (\<forall>B'. basis B' \<longrightarrow> sum w B \<le> sum w B')"

subsubsection \<open>preparation\<close>

fun in_sort_edge where
   "in_sort_edge x [] = [x]"
 | "in_sort_edge x (y#ys) = (if w x \<le> w y then x#y#ys else y# in_sort_edge x ys)"

lemma in_sort_edge: "sorted_wrt (\<lambda>e1 e2. w e1 \<le> w e2) L \<Longrightarrow> sorted_wrt (\<lambda>e1 e2. w e1 \<le> w e2) (in_sort_edge x L)"
  apply(induct L ) by auto

lemma in_sort_edge_distinct: "x \<notin> set L \<Longrightarrow> distinct L \<Longrightarrow> distinct (in_sort_edge x L)"
apply(induct L) by auto

lemma finite_sorted_edge_distinct:
  assumes "finite S"
  obtains L where "distinct L" "sorted_wrt (\<lambda>e1 e2. w e1 \<le> w e2) L" "S = set L"
proof -
  {
    have "\<exists>L.  distinct L \<and> sorted_wrt (\<lambda>e1 e2. w e1 \<le> w e2) L \<and> S = set L"
      using assms
      apply(induct S)
       apply(clarsimp)
      apply(clarsimp)
      subgoal for x L apply(rule exI[where x="in_sort_edge x L"])
        by (auto simp: in_sort_edge in_sort_edge_distinct)
    done
  }
  with that show ?thesis by blast
qed

abbreviation "wsorted == sorted_wrt_w w"

lemma sum_list_map_cons: "sum_list (map w (y # ys)) = w y + sum_list (map w ys)" by auto

lemma exists_greater:
  assumes  len: "length F = length F'"
      and sum: "sum_list (map w F) > sum_list (map w F')"
    shows "\<exists>i<length F. w (F ! i) > w (F' ! i)"
using len sum
proof (induct rule: list_induct2)
  case (Cons x xs y ys)
  show ?case
  proof(cases "w y < w x")
    case True
    then show ?thesis by auto
  next
    case False
    from False Cons(3) have "sum_list (map w ys) < sum_list (map w xs)"
      apply(simp add: sum_list_map_cons)
      by (meson add_mono leD le_less_linear)
    from Cons(2)[OF this] show ?thesis by auto
  qed
qed simp

lemma wsorted_Cons: "wsorted (x#xs) = (wsorted xs & (ALL y:set xs. w x <= w y))"
  by (induct xs arbitrary: x) auto

lemma wsorted_nth_mono: assumes "wsorted L" "i\<le>j" "j<length L"
  shows "w (L!i) \<le> w (L!j)"
  using assms apply (induct L arbitrary: i j rule: list.induct) by (auto simp: nth_Cons' wsorted_Cons)

(**
  limi T g is the set T restricted
     to elements only with weight
    strictly smaller than g.
*)
definition "limi T g == {e. e\<in>T \<and> w e < g}"

lemma limi_subset: "limi T g \<subseteq> T" unfolding limi_def by auto

lemma limi_mono: "A \<subseteq> B \<Longrightarrow> limi A g \<subseteq> limi B g"
unfolding limi_def by auto

(*
  let F be a set of elements
  limi F g is the set F restricted to elements with weight smaller than g
  let E be a set of elements we want to exclude

  no_smallest_element_skipped E F says,
     that going greedyly over (carrier-E), every every element,
     that did not render the akkumulated set dependent, was added to the set F.
*)
definition "no_smallest_element_skipped E F = (\<forall>e\<in>carrier - E. \<forall>g>w e. indep (insert e (limi F g)) \<longrightarrow> (e \<in> limi F g))"

lemma no_smallest_element_skipped_empty[simp]: "no_smallest_element_skipped carrier {}"
  by(auto simp: no_smallest_element_skipped_def)

lemma greedy_approach_leads_to_minBasis: assumes "indep F"
  and "\<forall>e\<in>carrier - F. \<not> indep (insert e F)"
  and "no_smallest_element_skipped {} F"
  shows "minBasis F"
proof (rule ccontr)
  \<comment> \<open>from our assumptions we have that F is a basis\<close>
  from assms have bF: "basis F" using indep_not_basis by blast
  \<comment> \<open>towards a contradiction, assume F is not a minimum Basis\<close>
  assume notmin: "\<not> minBasis F"
  \<comment> \<open>then we can get a smaller Basis B\<close>
  from bF notmin[unfolded minBasis_def] obtain B where bB: "basis B" and sum: "sum w B < sum w F"
    by force
  \<comment> \<open>lets us obtain two sorted lists for the bases F and B\<close>
  from bF basis_finite finite_sorted_edge_distinct
    obtain FL where dF[simp]: "distinct FL" and wF[simp]: "wsorted FL" and sF[simp]: "F = set FL"
    by blast
  from bB basis_finite finite_sorted_edge_distinct
    obtain BL where dB[simp]: "distinct BL" and wB[simp]: "wsorted BL" and sB[simp]: "B = set BL"
      by blast
  \<comment> \<open>as basis F has more total weight than basis B ...\<close>
  from sum have suml: "sum_list (map w BL) < sum_list (map w FL)"
    by(simp add: sum.distinct_set_conv_list[symmetric])
  from bB bF have "card B = card F"
    using basis_card by blast
  then have l: "length FL = length BL"
    by (simp add: distinct_card)
  \<comment> \<open>... there exists an index i such that the ith element of the BL is strictly smaller
      than the ith element of FL \<close>
  from exists_greater[OF (*_ _ _ _*) l suml] obtain i where i: "i<length FL" and gr: "w (BL ! i) < w (FL ! i)"
    by auto
  let ?FL_restricted = "limi (set FL) (w (FL ! i))"

  \<comment> \<open>now let us look at the two independent sets X and Y:
        let X and Y be the set if we take the first i-1 elements of BL
         and the first i elements of FL respectively.
      We want to use the augment property of Matroids in order to show that we must have skipped
      and optimal element, which then contradicts our assumption. \<close>
  let ?X = "take i FL"
  have X_size: "card (set ?X) = i" using i
    by (simp add: distinct_card)
  have X_indep: "indep (set ?X)" using bF
    using indep_iff_subset_basis set_take_subset by force

  let ?Y = "take (Suc i) BL"
  have Y_size: "card (set ?Y) = Suc i" using i l
    by (simp add: distinct_card)
  have Y_indep: "indep (set ?Y)" using bB
    using indep_iff_subset_basis set_take_subset by force

  have "card (set ?X) < card (set ?Y)" using X_size Y_size by simp

  \<comment> \<open>X and Y are independent and X is smaller than Y, thus we can augment X with some element x\<close>
  with Y_indep X_indep
    obtain x where x: "x\<in>set (take (Suc i) BL) - set ?X" and indepX: "indep (insert x (set ?X))"
      using augment by auto

  \<comment> \<open>we know many things about x now, i.e. x weights strictly less than the ith element of FL ...\<close>
  have "x\<in>carrier"  using indepX indep_subset_carrier by blast
  from x have xs: "x\<in>set (take (Suc i) BL)" and xnX: "x \<notin> set ?X" by auto
  from xs have "w x \<le> w (BL ! i)" using wB
    by (metis List.length_take Lists_Thms.nth_take Suc_leI Suc_le_mono dB distinct_Ex1 distinct_take i local.l min_Suc_gt(2) wsorted_nth_mono)
      (* FIXME *)
  then have k: "w x < w (FL ! i)" using gr by auto

  \<comment> \<open>... and that adding x to X gives us an independent set\<close>
  have "?FL_restricted \<subseteq> set ?X"
    unfolding  limi_def apply auto
    by (smt dF i index_nth_id leD leI linorder_linear mem_Collect_eq set_conv_nth set_take_if_index wF wsorted_nth_mono) (* FIXME *)
  have z': "insert x ?FL_restricted \<subseteq> insert x (set ?X)"
    using xnX `?FL_restricted \<subseteq> set (take i FL)` by auto
  from indep_subset[OF indepX z'] have add_x_stay_indep: "indep (insert x ?FL_restricted)" .

  \<comment> \<open>... finally this means that we must have taken the element during our greedy algorithm\<close>
  from `no_smallest_element_skipped {} F` `x\<in>carrier` `w x < w (FL ! i)` add_x_stay_indep
    have "x \<in> ?FL_restricted"  by (auto dest: no_smallest_element_skippedD)
  with `?FL_restricted \<subseteq> set ?X` have "x \<in> set ?X"  by auto

  \<comment> \<open>... but we actually didn't. This finishes our proof by contradiction.\<close>
  with xnX show "False" by auto
qed

lemma assumes createsCycle: "\<not> indep (insert e F)"
       and    I: "no_smallest_element_skipped (E\<union>{e}) F"
       and    sorted: "(\<forall>x\<in>F.\<forall>y\<in>(E\<union>{e}). w x \<le> w y)"
     shows I_preservation1': "no_smallest_element_skipped E F"
  unfolding no_smallest_element_skipped_def
proof (clarsimp)
  fix x g
  assume x: "x \<in> carrier"  "x \<notin> E"  "w x < g"
  assume f: "indep (insert x (limi F g))"
  show "(x \<in> limi F g)"
  proof (cases "x=e")
    case True
    from True have "limi F g = F"
      unfolding limi_def using \<open>w x < g\<close> sorted by fastforce
    with createsCycle f True have "False" by auto
    then show ?thesis by simp
  next
    case False
    show ?thesis
    apply(rule I[THEN no_smallest_element_skippedD, OF _ \<open>w x < g\<close>])
    using x f False
    by (auto simp add: )
  qed
qed

lemma I_preservation2:
    assumes "e \<in> E" "\<forall>e\<in>carrier - E - F. \<not> indep (insert e F)"
    shows  "(\<forall>x\<in>carrier - (E - {e}) - insert e F. \<not> indep (insert x (insert e F)))"
using assms  by (smt Diff_insert Diff_insert2 indep_subset insert_Diff insert_commute subset_insertI)

lemma I_preservation3':
  assumes I: "no_smallest_element_skipped (E\<union>{e}) F"
  shows "no_smallest_element_skipped E (insert e F)"
  unfolding no_smallest_element_skipped_def
proof (clarsimp)
  fix x g
  assume xc: "x \<in> carrier"
  assume x: "x \<notin> E"
  assume wx: "w x < g"
  assume f: "indep (insert x (limi (insert e F) g))"
  show "(x \<in> limi (insert e F) g)"
  proof(cases "x=e")
    case True
    then show ?thesis unfolding limi_def
      using wx by blast
  next
    case False
    have ind: "indep (insert x (limi F g))" apply(rule indep_subset[OF f]) using limi_mono by blast
    have "indep (insert x (limi F g)) \<Longrightarrow> x \<in> limi F g"
      apply(rule I[THEN no_smallest_element_skippedD]) using False xc wx x by auto
    with ind show ?thesis using limi_mono by blast
  qed
qed

definition I_minWeightBasis_fine where
  "I_minWeightBasis_fine == \<lambda>(T,E). indep T
                \<and> T \<subseteq> carrier
                 \<and> E \<subseteq> carrier  \<and> T \<inter> E = {}
                 \<and> (\<forall>x\<in>T.\<forall>y\<in>E. w x \<le> w y)
                \<and> (\<forall>e\<in>carrier-E-T. ~indep (insert e T))
                 \<and> no_smallest_element_skipped E T"

lemma I_minWeightBasis_fineD:
  assumes
   "I_minWeightBasis_fine (T,E)"
 shows"indep T" "\<And>e. e\<in>carrier-E-T \<Longrightarrow> ~indep (insert e T)"
    "E \<subseteq> carrier" "\<And>x y. x\<in>T \<Longrightarrow> y\<in>E \<Longrightarrow> w x \<le> w y" "T \<inter> E = {}" "T \<subseteq> carrier"
    "no_smallest_element_skipped E T"
  using assms by(auto simp: no_smallest_element_skipped_def I_minWeightBasis_fine_def)

lemma I_minWeightBasis_fineI:
  assumes "indep T" "\<And>e. e\<in>carrier-E-T \<Longrightarrow> ~indep (insert e T)"
    "E \<subseteq> carrier" "\<And>x y. x\<in>T \<Longrightarrow> y\<in>E \<Longrightarrow> w x \<le> w y" "T \<inter> E = {}" "T \<subseteq> carrier"
    "no_smallest_element_skipped E T"
  shows "I_minWeightBasis_fine (T,E)"
  using assms by(auto simp: no_smallest_element_skipped_def I_minWeightBasis_fine_def)

lemma I_minWeightBasis_fineG: "I_minWeightBasis_fine (T,E) \<Longrightarrow> no_smallest_element_skipped E T" by(auto simp: no_smallest_element_skipped_def I_minWeightBasis_fine_def)

lemma I_minWeightBasis_sorted: "I_minWeightBasis_fine (T,E) \<Longrightarrow> (\<forall>x\<in>T.\<forall>y\<in>E. w x \<le> w y)" by(auto simp: no_smallest_element_skipped_def I_minWeightBasis_fine_def)

end

locale minWeightBasis_time = minWeightBasis +
  fixes sorted_carrier_time :: nat
    and  empty_basis_time indep_test_time insert_time :: nat
begin
subsection \<open>Refinement to an algorithm using sorted lists\<close>

  definition (in -) "obtain_sorted_carrier_aux sct c w \<equiv> SPECT (emb (\<lambda>L. sorted_wrt_w w L \<and> distinct L \<and> set L = c) sct)"

  abbreviation "obtain_sorted_carrier \<equiv> obtain_sorted_carrier_aux sorted_carrier_time carrier w"

section \<open>minWeightBasis algorithm with nfoldi\<close>

abbreviation "empty_basis \<equiv> {}"

definition (in -) minWeightBasis3_aux where
  "minWeightBasis3_aux osc_t c we ebt itt it ind eb \<equiv> do {
        l \<leftarrow> obtain_sorted_carrier_aux osc_t c we ;
        ASSERT (set l = c);
        s \<leftarrow> SPECT [eb\<mapsto>ebt];
        T \<leftarrow> nfoldli l (\<lambda>_. True)
        (\<lambda>e T. do {
            ASSERT (e\<notin>T \<and> ind T \<and> e\<in>c \<and> T\<subseteq>c);
            b \<leftarrow> SPECT [ind (insert e T) \<mapsto> itt];
            if b then
              SPECT [(insert e T)\<mapsto>it]
            else
              RETURNT T
        }) s;
        RETURNT T
      }"

abbreviation "minWeightBasis3 \<equiv> minWeightBasis3_aux sorted_carrier_time carrier w empty_basis_time
                                     indep_test_time insert_time indep empty_basis"

lemma I_minWeightBasis_fine_empty: "I_minWeightBasis_fine ({}, carrier)"
  by (auto simp: I_minWeightBasis_fine_def)

lemma I_minWeightBasis_fine_final: "I_minWeightBasis_fine (T, {}) \<Longrightarrow> minBasis T"
  by(auto simp: greedy_approach_leads_to_minBasis I_minWeightBasis_fine_def)

lemma preservation_else: "set x = carrier \<Longrightarrow>
    x = l1 @ xa # l2 \<Longrightarrow> I_minWeightBasis_fine (\<sigma>, set (xa # l2))
     \<Longrightarrow> indep \<sigma>   \<Longrightarrow> \<not> indep (insert xa \<sigma>) \<Longrightarrow> I_minWeightBasis_fine (\<sigma>, set l2)"
  apply(rule I_minWeightBasis_fineI)
  subgoal by simp
  subgoal by (auto simp: DiffD2 I_minWeightBasis_fine_def)
  subgoal by auto
  subgoal by(auto simp: I_minWeightBasis_fine_def)
  subgoal by(auto simp: I_minWeightBasis_fine_def)
  subgoal by(auto simp: I_minWeightBasis_fine_def)
  subgoal apply (rule I_preservation1')
    by(auto intro!:  simp: I_minWeightBasis_fine_def)
  done

lemma I_preservation2':
  assumes "e \<in> E" "\<forall>e\<in>carrier - E - F. \<not> indep (insert e F)"
    and "x\<in>carrier - (E - {e}) - insert e F"
    shows  "\<not> indep (insert x (insert e F))"
  using assms I_preservation2 by auto

lemma preservation_if: "wsorted x \<Longrightarrow> distinct x \<Longrightarrow> set x = carrier \<Longrightarrow>
    x = l1 @ xa # l2 \<Longrightarrow> I_minWeightBasis_fine (\<sigma>, set (xa # l2)) \<Longrightarrow> True \<Longrightarrow> xa \<notin> \<sigma>
   \<Longrightarrow> xa \<in> carrier \<Longrightarrow> indep (insert xa \<sigma>) \<Longrightarrow> I_minWeightBasis_fine (insert xa \<sigma>, set l2)"
  apply(rule I_minWeightBasis_fineI)
  subgoal by simp
  subgoal unfolding I_minWeightBasis_fine_def apply(rule I_preservation2'[where E="set (xa # l2)"])
    by simp_all
  subgoal by auto
  subgoal by (metis insert_iff list.set(2) I_minWeightBasis_sorted sorted_wrt_append wsorted_Cons)
  subgoal by(auto simp: I_minWeightBasis_fine_def)
  subgoal by(auto simp: I_minWeightBasis_fine_def)
  subgoal apply (rule I_preservation3')
    by(auto intro!:  simp: I_minWeightBasis_fine_def)
  done

definition "minBasis_time = sorted_carrier_time +  empty_basis_time
             +  card carrier * (indep_test_time + insert_time)"

lemma le_Id: "M \<le> M' \<Longrightarrow> M \<le> \<Down> Id M'"
  by auto

theorem minWeightBasis3_refine: "minWeightBasis3 \<le> \<Down> Id (SPECT (emb minBasis minBasis_time))"
  unfolding minWeightBasis3_aux_def obtain_sorted_carrier_aux_def
  unfolding nfoldliIE_def[where E="indep_test_time + insert_time" and I="\<lambda>l1 l2 s. I_minWeightBasis_fine (s,set l2)", symmetric]
  apply(rule le_Id)
  apply(rule T_specifies_I)
  unfolding nfoldliIE'_def[symmetric]
  apply(vcg' \<open>-\<close> rules: nfoldliIE'_rule  )
  unfolding Some_le_emb'_conv
       apply (safe)
  oops

lemmas f = nfoldliIE_rule[where  t="card carrier * (indep_test_time + insert_time)" and
                    P="\<lambda>T. I_minWeightBasis_fine (T, {})", THEN T_specifies_rev, THEN T_conseq4]
theorem minWeightBasis3_refine: "minWeightBasis3 \<le> \<Down> Id (SPECT (emb minBasis minBasis_time))"
  unfolding minWeightBasis3_aux_def obtain_sorted_carrier_aux_def
  unfolding nfoldliIE_def[where E="indep_test_time + insert_time" and I="\<lambda>l1 l2 s. I_minWeightBasis_fine (s,set l2)", symmetric]
  apply(rule le_Id)
    apply(rule T_specifies_I)
  apply(vcg' \<open>-\<close> rules: f )

  subgoal by (auto simp: I_minWeightBasis_fine_empty)
  subgoal (* loop body *)
    apply(rule T_specifies_I)
    apply(vcg' \<open>-\<close> rules: f )
      apply(simp_all add: Some_le_emb'_conv )

    subgoal apply(rule preservation_if) by (auto dest!: I_minWeightBasis_fineD(5))
    subgoal apply(rule preservation_else) by (auto dest!: I_minWeightBasis_fineD(1))

    (* asserts *)
    subgoal by (auto      simp: I_minWeightBasis_fine_def)
    done
  subgoal by simp
  subgoal by simp

  subgoal by (auto  simp:  distinct_card Some_le_emb'_conv )
  subgoal by (auto  simp: I_minWeightBasis_fine_final minBasis_time_def vcg_simp_rules)
  subgoal by auto
  done

end

end


(*  Title:      HOL/Conditionally_Complete_Lattices.thy
    Author:     Amine Chaieb and L C Paulson, University of Cambridge
    Author:     Johannes Hölzl, TU München
    Author:     Luke S. Serafin, Carnegie Mellon University
*)

section \<open>Conditionally-complete Lattices\<close>

theory Conditionally_Complete_Lattices
imports Finite_Set Lattices_Big Set_Interval
begin

lemma (in linorder) Sup_fin_eq_Max: "finite X \<Longrightarrow> X \<noteq> {} \<Longrightarrow> Sup_fin X = Max X"
  by (induct X rule: finite_ne_induct) (simp_all add: sup_max)

lemma (in linorder) Inf_fin_eq_Min: "finite X \<Longrightarrow> X \<noteq> {} \<Longrightarrow> Inf_fin X = Min X"
  by (induct X rule: finite_ne_induct) (simp_all add: inf_min)

context preorder
begin

definition "bdd_above A \<longleftrightarrow> (\<exists>M. \<forall>x \<in> A. x \<le> M)"
definition "bdd_below A \<longleftrightarrow> (\<exists>m. \<forall>x \<in> A. m \<le> x)"

lemma bdd_aboveI[intro]: "(\<And>x. x \<in> A \<Longrightarrow> x \<le> M) \<Longrightarrow> bdd_above A"
  by (auto simp: bdd_above_def)

lemma bdd_belowI[intro]: "(\<And>x. x \<in> A \<Longrightarrow> m \<le> x) \<Longrightarrow> bdd_below A"
  by (auto simp: bdd_below_def)

lemma bdd_aboveI2: "(\<And>x. x \<in> A \<Longrightarrow> f x \<le> M) \<Longrightarrow> bdd_above (f`A)"
  by force

lemma bdd_belowI2: "(\<And>x. x \<in> A \<Longrightarrow> m \<le> f x) \<Longrightarrow> bdd_below (f`A)"
  by force

lemma bdd_above_empty [simp, intro]: "bdd_above {}"
  unfolding bdd_above_def by auto

lemma bdd_below_empty [simp, intro]: "bdd_below {}"
  unfolding bdd_below_def by auto

lemma bdd_above_mono: "bdd_above B \<Longrightarrow> A \<subseteq> B \<Longrightarrow> bdd_above A"
  by (metis (full_types) bdd_above_def order_class.le_neq_trans psubsetD)

lemma bdd_below_mono: "bdd_below B \<Longrightarrow> A \<subseteq> B \<Longrightarrow> bdd_below A"
  by (metis bdd_below_def order_class.le_neq_trans psubsetD)

lemma bdd_above_Int1 [simp]: "bdd_above A \<Longrightarrow> bdd_above (A \<inter> B)"
  using bdd_above_mono by auto

lemma bdd_above_Int2 [simp]: "bdd_above B \<Longrightarrow> bdd_above (A \<inter> B)"
  using bdd_above_mono by auto

lemma bdd_below_Int1 [simp]: "bdd_below A \<Longrightarrow> bdd_below (A \<inter> B)"
  using bdd_below_mono by auto

lemma bdd_below_Int2 [simp]: "bdd_below B \<Longrightarrow> bdd_below (A \<inter> B)"
  using bdd_below_mono by auto

lemma bdd_above_Ioo [simp, intro]: "bdd_above {a <..< b}"
  by (auto simp add: bdd_above_def intro!: exI[of _ b] less_imp_le)

lemma bdd_above_Ico [simp, intro]: "bdd_above {a ..< b}"
  by (auto simp add: bdd_above_def intro!: exI[of _ b] less_imp_le)

lemma bdd_above_Iio [simp, intro]: "bdd_above {..< b}"
  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)

lemma bdd_above_Ioc [simp, intro]: "bdd_above {a <.. b}"
  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)

lemma bdd_above_Icc [simp, intro]: "bdd_above {a .. b}"
  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)

lemma bdd_above_Iic [simp, intro]: "bdd_above {.. b}"
  by (auto simp add: bdd_above_def intro: exI[of _ b] less_imp_le)

lemma bdd_below_Ioo [simp, intro]: "bdd_below {a <..< b}"
  by (auto simp add: bdd_below_def intro!: exI[of _ a] less_imp_le)

lemma bdd_below_Ioc [simp, intro]: "bdd_below {a <.. b}"
  by (auto simp add: bdd_below_def intro!: exI[of _ a] less_imp_le)

lemma bdd_below_Ioi [simp, intro]: "bdd_below {a <..}"
  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)

lemma bdd_below_Ico [simp, intro]: "bdd_below {a ..< b}"
  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)

lemma bdd_below_Icc [simp, intro]: "bdd_below {a .. b}"
  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)

lemma bdd_below_Ici [simp, intro]: "bdd_below {a ..}"
  by (auto simp add: bdd_below_def intro: exI[of _ a] less_imp_le)

end

lemma (in order_top) bdd_above_top[simp, intro!]: "bdd_above A"
  by (rule bdd_aboveI[of _ top]) simp

lemma (in order_bot) bdd_above_bot[simp, intro!]: "bdd_below A"
  by (rule bdd_belowI[of _ bot]) simp

lemma bdd_above_image_mono: "mono f \<Longrightarrow> bdd_above A \<Longrightarrow> bdd_above (f`A)"
  by (auto simp: bdd_above_def mono_def)

lemma bdd_below_image_mono: "mono f \<Longrightarrow> bdd_below A \<Longrightarrow> bdd_below (f`A)"
  by (auto simp: bdd_below_def mono_def)

lemma bdd_above_image_antimono: "antimono f \<Longrightarrow> bdd_below A \<Longrightarrow> bdd_above (f`A)"
  by (auto simp: bdd_above_def bdd_below_def antimono_def)

lemma bdd_below_image_antimono: "antimono f \<Longrightarrow> bdd_above A \<Longrightarrow> bdd_below (f`A)"
  by (auto simp: bdd_above_def bdd_below_def antimono_def)

lemma
  fixes X :: "'a::ordered_ab_group_add set"
  shows bdd_above_uminus[simp]: "bdd_above (uminus ` X) \<longleftrightarrow> bdd_below X"
    and bdd_below_uminus[simp]: "bdd_below (uminus ` X) \<longleftrightarrow> bdd_above X"
  using bdd_above_image_antimono[of uminus X] bdd_below_image_antimono[of uminus "uminus`X"]
  using bdd_below_image_antimono[of uminus X] bdd_above_image_antimono[of uminus "uminus`X"]
  by (auto simp: antimono_def image_image)

context lattice
begin

lemma bdd_above_insert [simp]: "bdd_above (insert a A) = bdd_above A"
  by (auto simp: bdd_above_def intro: le_supI2 sup_ge1)

lemma bdd_below_insert [simp]: "bdd_below (insert a A) = bdd_below A"
  by (auto simp: bdd_below_def intro: le_infI2 inf_le1)

lemma bdd_finite [simp]:
  assumes "finite A" shows bdd_above_finite: "bdd_above A" and bdd_below_finite: "bdd_below A"
  using assms by (induct rule: finite_induct, auto)

lemma bdd_above_Un [simp]: "bdd_above (A \<union> B) = (bdd_above A \<and> bdd_above B)"
proof
  assume "bdd_above (A \<union> B)"
  thus "bdd_above A \<and> bdd_above B" unfolding bdd_above_def by auto
next
  assume "bdd_above A \<and> bdd_above B"
  then obtain a b where "\<forall>x\<in>A. x \<le> a" "\<forall>x\<in>B. x \<le> b" unfolding bdd_above_def by auto
  hence "\<forall>x \<in> A \<union> B. x \<le> sup a b" by (auto intro: Un_iff le_supI1 le_supI2)
  thus "bdd_above (A \<union> B)" unfolding bdd_above_def ..
qed

lemma bdd_below_Un [simp]: "bdd_below (A \<union> B) = (bdd_below A \<and> bdd_below B)"
proof
  assume "bdd_below (A \<union> B)"
  thus "bdd_below A \<and> bdd_below B" unfolding bdd_below_def by auto
next
  assume "bdd_below A \<and> bdd_below B"
  then obtain a b where "\<forall>x\<in>A. a \<le> x" "\<forall>x\<in>B. b \<le> x" unfolding bdd_below_def by auto
  hence "\<forall>x \<in> A \<union> B. inf a b \<le> x" by (auto intro: Un_iff le_infI1 le_infI2)
  thus "bdd_below (A \<union> B)" unfolding bdd_below_def ..
qed

lemma bdd_above_sup[simp]: "bdd_above ((\<lambda>x. sup (f x) (g x)) ` A) \<longleftrightarrow> bdd_above (f`A) \<and> bdd_above (g`A)"
  by (auto simp: bdd_above_def intro: le_supI1 le_supI2)

lemma bdd_below_inf[simp]: "bdd_below ((\<lambda>x. inf (f x) (g x)) ` A) \<longleftrightarrow> bdd_below (f`A) \<and> bdd_below (g`A)"
  by (auto simp: bdd_below_def intro: le_infI1 le_infI2)

end

text \<open>

To avoid name classes with the @{class complete_lattice}-class we prefix @{const Sup} and
@{const Inf} in theorem names with c.

\<close>

class conditionally_complete_lattice = lattice + Sup + Inf +
  assumes cInf_lower: "x \<in> X \<Longrightarrow> bdd_below X \<Longrightarrow> Inf X \<le> x"
    and cInf_greatest: "X \<noteq> {} \<Longrightarrow> (\<And>x. x \<in> X \<Longrightarrow> z \<le> x) \<Longrightarrow> z \<le> Inf X"
  assumes cSup_upper: "x \<in> X \<Longrightarrow> bdd_above X \<Longrightarrow> x \<le> Sup X"
    and cSup_least: "X \<noteq> {} \<Longrightarrow> (\<And>x. x \<in> X \<Longrightarrow> x \<le> z) \<Longrightarrow> Sup X \<le> z"
begin

lemma cSup_upper2: "x \<in> X \<Longrightarrow> y \<le> x \<Longrightarrow> bdd_above X \<Longrightarrow> y \<le> Sup X"
  by (metis cSup_upper order_trans)

lemma cInf_lower2: "x \<in> X \<Longrightarrow> x \<le> y \<Longrightarrow> bdd_below X \<Longrightarrow> Inf X \<le> y"
  by (metis cInf_lower order_trans)

lemma cSup_mono: "B \<noteq> {} \<Longrightarrow> bdd_above A \<Longrightarrow> (\<And>b. b \<in> B \<Longrightarrow> \<exists>a\<in>A. b \<le> a) \<Longrightarrow> Sup B \<le> Sup A"
  by (metis cSup_least cSup_upper2)

lemma cInf_mono: "B \<noteq> {} \<Longrightarrow> bdd_below A \<Longrightarrow> (\<And>b. b \<in> B \<Longrightarrow> \<exists>a\<in>A. a \<le> b) \<Longrightarrow> Inf A \<le> Inf B"
  by (metis cInf_greatest cInf_lower2)

lemma cSup_subset_mono: "A \<noteq> {} \<Longrightarrow> bdd_above B \<Longrightarrow> A \<subseteq> B \<Longrightarrow> Sup A \<le> Sup B"
  by (metis cSup_least cSup_upper subsetD)

lemma cInf_superset_mono: "A \<noteq> {} \<Longrightarrow> bdd_below B \<Longrightarrow> A \<subseteq> B \<Longrightarrow> Inf B \<le> Inf A"
  by (metis cInf_greatest cInf_lower subsetD)

lemma cSup_eq_maximum: "z \<in> X \<Longrightarrow> (\<And>x. x \<in> X \<Longrightarrow> x \<le> z) \<Longrightarrow> Sup X = z"
  by (intro antisym cSup_upper[of z X] cSup_least[of X z]) auto

lemma cInf_eq_minimum: "z \<in> X \<Longrightarrow> (\<And>x. x \<in> X \<Longrightarrow> z \<le> x) \<Longrightarrow> Inf X = z"
  by (intro antisym cInf_lower[of z X] cInf_greatest[of X z]) auto

lemma cSup_le_iff: "S \<noteq> {} \<Longrightarrow> bdd_above S \<Longrightarrow> Sup S \<le> a \<longleftrightarrow> (\<forall>x\<in>S. x \<le> a)"
  by (metis order_trans cSup_upper cSup_least)

lemma le_cInf_iff: "S \<noteq> {} \<Longrightarrow> bdd_below S \<Longrightarrow> a \<le> Inf S \<longleftrightarrow> (\<forall>x\<in>S. a \<le> x)"
  by (metis order_trans cInf_lower cInf_greatest)

lemma cSup_eq_non_empty:
  assumes 1: "X \<noteq> {}"
  assumes 2: "\<And>x. x \<in> X \<Longrightarrow> x \<le> a"
  assumes 3: "\<And>y. (\<And>x. x \<in> X \<Longrightarrow> x \<le> y) \<Longrightarrow> a \<le> y"
  shows "Sup X = a"
  by (intro 3 1 antisym cSup_least) (auto intro: 2 1 cSup_upper)

lemma cInf_eq_non_empty:
  assumes 1: "X \<noteq> {}"
  assumes 2: "\<And>x. x \<in> X \<Longrightarrow> a \<le> x"
  assumes 3: "\<And>y. (\<And>x. x \<in> X \<Longrightarrow> y \<le> x) \<Longrightarrow> y \<le> a"
  shows "Inf X = a"
  by (intro 3 1 antisym cInf_greatest) (auto intro: 2 1 cInf_lower)

lemma cInf_cSup: "S \<noteq> {} \<Longrightarrow> bdd_below S \<Longrightarrow> Inf S = Sup {x. \<forall>s\<in>S. x \<le> s}"
  by (rule cInf_eq_non_empty) (auto intro!: cSup_upper cSup_least simp: bdd_below_def)

lemma cSup_cInf: "S \<noteq> {} \<Longrightarrow> bdd_above S \<Longrightarrow> Sup S = Inf {x. \<forall>s\<in>S. s \<le> x}"
  by (rule cSup_eq_non_empty) (auto intro!: cInf_lower cInf_greatest simp: bdd_above_def)

lemma cSup_insert: "X \<noteq> {} \<Longrightarrow> bdd_above X \<Longrightarrow> Sup (insert a X) = sup a (Sup X)"
  by (intro cSup_eq_non_empty) (auto intro: le_supI2 cSup_upper cSup_least)

lemma cInf_insert: "X \<noteq> {} \<Longrightarrow> bdd_below X \<Longrightarrow> Inf (insert a X) = inf a (Inf X)"
  by (intro cInf_eq_non_empty) (auto intro: le_infI2 cInf_lower cInf_greatest)

lemma cSup_singleton [simp]: "Sup {x} = x"
  by (intro cSup_eq_maximum) auto

lemma cInf_singleton [simp]: "Inf {x} = x"
  by (intro cInf_eq_minimum) auto

lemma cSup_insert_If:  "bdd_above X \<Longrightarrow> Sup (insert a X) = (if X = {} then a else sup a (Sup X))"
  using cSup_insert[of X] by simp

lemma cInf_insert_If: "bdd_below X \<Longrightarrow> Inf (insert a X) = (if X = {} then a else inf a (Inf X))"
  using cInf_insert[of X] by simp

lemma le_cSup_finite: "finite X \<Longrightarrow> x \<in> X \<Longrightarrow> x \<le> Sup X"
proof (induct X arbitrary: x rule: finite_induct)
  case (insert x X y) then show ?case
    by (cases "X = {}") (auto simp: cSup_insert intro: le_supI2)
qed simp

lemma cInf_le_finite: "finite X \<Longrightarrow> x \<in> X \<Longrightarrow> Inf X \<le> x"
proof (induct X arbitrary: x rule: finite_induct)
  case (insert x X y) then show ?case
    by (cases "X = {}") (auto simp: cInf_insert intro: le_infI2)
qed simp

lemma cSup_eq_Sup_fin: "finite X \<Longrightarrow> X \<noteq> {} \<Longrightarrow> Sup X = Sup_fin X"
  by (induct X rule: finite_ne_induct) (simp_all add: cSup_insert)

lemma cInf_eq_Inf_fin: "finite X \<Longrightarrow> X \<noteq> {} \<Longrightarrow> Inf X = Inf_fin X"
  by (induct X rule: finite_ne_induct) (simp_all add: cInf_insert)

lemma cSup_atMost[simp]: "Sup {..x} = x"
  by (auto intro!: cSup_eq_maximum)

lemma cSup_greaterThanAtMost[simp]: "y < x \<Longrightarrow> Sup {y<..x} = x"
  by (auto intro!: cSup_eq_maximum)

lemma cSup_atLeastAtMost[simp]: "y \<le> x \<Longrightarrow> Sup {y..x} = x"
  by (auto intro!: cSup_eq_maximum)

lemma cInf_atLeast[simp]: "Inf {x..} = x"
  by (auto intro!: cInf_eq_minimum)

lemma cInf_atLeastLessThan[simp]: "y < x \<Longrightarrow> Inf {y..<x} = y"
  by (auto intro!: cInf_eq_minimum)

lemma cInf_atLeastAtMost[simp]: "y \<le> x \<Longrightarrow> Inf {y..x} = y"
  by (auto intro!: cInf_eq_minimum)

lemma cINF_lower: "bdd_below (f ` A) \<Longrightarrow> x \<in> A \<Longrightarrow> INFIMUM A f \<le> f x"
  using cInf_lower [of _ "f ` A"] by simp

lemma cINF_greatest: "A \<noteq> {} \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> m \<le> f x) \<Longrightarrow> m \<le> INFIMUM A f"
  using cInf_greatest [of "f ` A"] by auto

lemma cSUP_upper: "x \<in> A \<Longrightarrow> bdd_above (f ` A) \<Longrightarrow> f x \<le> SUPREMUM A f"
  using cSup_upper [of _ "f ` A"] by simp

lemma cSUP_least: "A \<noteq> {} \<Longrightarrow> (\<And>x. x \<in> A \<Longrightarrow> f x \<le> M) \<Longrightarrow> SUPREMUM A f \<le> M"
  using cSup_least [of "f ` A"] by auto

lemma cINF_lower2: "bdd_below (f ` A) \<Longrightarrow> x \<in> A \<Longrightarrow> f x \<le> u \<Longrightarrow> INFIMUM A f \<le> u"
  by (auto intro: cINF_lower order_trans)

lemma cSUP_upper2: "bdd_above (f ` A) \<Longrightarrow> x \<in> A \<Longrightarrow> u \<le> f x \<Longrightarrow> u \<le> SUPREMUM A f"
  by (auto intro: cSUP_upper order_trans)

lemma cSUP_const [simp]: "A \<noteq> {} \<Longrightarrow> (SUP x:A. c) = c"
  by (intro antisym cSUP_least) (auto intro: cSUP_upper)

lemma cINF_const [simp]: "A \<noteq> {} \<Longrightarrow> (INF x:A. c) = c"
  by (intro antisym cINF_greatest) (auto intro: cINF_lower)

lemma le_cINF_iff: "A \<noteq> {} \<Longrightarrow> bdd_below (f ` A) \<Longrightarrow> u \<le> INFIMUM A f \<longleftrightarrow> (\<forall>x\<in>A. u \<le> f x)"
  by (metis cINF_greatest cINF_lower order_trans)

lemma cSUP_le_iff: "A \<noteq> {} \<Longrightarrow> bdd_above (f ` A) \<Longrightarrow> SUPREMUM A f \<le> u \<longleftrightarrow> (\<forall>x\<in>A. f x \<le> u)"
  by (metis cSUP_least cSUP_upper order_trans)

lemma less_cINF_D: "bdd_below (f`A) \<Longrightarrow> y < (INF i:A. f i) \<Longrightarrow> i \<in> A \<Longrightarrow> y < f i"
  by (metis cINF_lower less_le_trans)

lemma cSUP_lessD: "bdd_above (f`A) \<Longrightarrow> (SUP i:A. f i) < y \<Longrightarrow> i \<in> A \<Longrightarrow> f i < y"
  by (metis cSUP_upper le_less_trans)

lemma cINF_insert: "A \<noteq> {} \<Longrightarrow> bdd_below (f ` A) \<Longrightarrow> INFIMUM (insert a A) f = inf (f a) (INFIMUM A f)"
  by (metis cInf_insert image_insert image_is_empty)

lemma cSUP_insert: "A \<noteq> {} \<Longrightarrow> bdd_above (f ` A) \<Longrightarrow> SUPREMUM (insert a A) f = sup (f a) (SUPREMUM A f)"
  by (metis cSup_insert image_insert image_is_empty)

lemma cINF_mono: "B \<noteq> {} \<Longrightarrow> bdd_below (f ` A) \<Longrightarrow> (\<And>m. m \<in> B \<Longrightarrow> \<exists>n\<in>A. f n \<le> g m) \<Longrightarrow> INFIMUM A f \<le> INFIMUM B g"
  using cInf_mono [of "g ` B" "f ` A"] by auto

lemma cSUP_mono: "A \<noteq> {} \<Longrightarrow> bdd_above (g ` B) \<Longrightarrow> (\<And>n. n \<in> A \<Longrightarrow> \<exists>m\<in>B. f n \<le> g m) \<Longrightarrow> SUPREMUM A f \<le> SUPREMUM B g"
  using cSup_mono [of "f ` A" "g ` B"] by auto

lemma cINF_superset_mono: "A \<noteq> {} \<Longrightarrow> bdd_below (g ` B) \<Longrightarrow> A \<subseteq> B \<Longrightarrow> (\<And>x. x \<in> B \<Longrightarrow> g x \<le> f x) \<Longrightarrow> INFIMUM B g \<le> INFIMUM A f"
  by (rule cINF_mono) auto

lemma cSUP_subset_mono: "A \<noteq> {} \<Longrightarrow> bdd_above (g ` B) \<Longrightarrow> A \<subseteq> B \<Longrightarrow> (\<And>x. x \<in> B \<Longrightarrow> f x \<le> g x) \<Longrightarrow> SUPREMUM A f \<le> SUPREMUM B g"
  by (rule cSUP_mono) auto

lemma less_eq_cInf_inter: "bdd_below A \<Longrightarrow> bdd_below B \<Longrightarrow> A \<inter> B \<noteq> {} \<Longrightarrow> inf (Inf A) (Inf B) \<le> Inf (A \<inter> B)"
  by (metis cInf_superset_mono lattice_class.inf_sup_ord(1) le_infI1)

lemma cSup_inter_less_eq: "bdd_above A \<Longrightarrow> bdd_above B \<Longrightarrow> A \<inter> B \<noteq> {} \<Longrightarrow> Sup (A \<inter> B) \<le> sup (Sup A) (Sup B) "
  by (metis cSup_subset_mono lattice_class.inf_sup_ord(1) le_supI1)

lemma cInf_union_distrib: "A \<noteq> {} \<Longrightarrow> bdd_below A \<Longrightarrow> B \<noteq> {} \<Longrightarrow> bdd_below B \<Longrightarrow> Inf (A \<union> B) = inf (Inf A) (Inf B)"
  by (intro antisym le_infI cInf_greatest cInf_lower) (auto intro: le_infI1 le_infI2 cInf_lower)

lemma cINF_union: "A \<noteq> {} \<Longrightarrow> bdd_below (f`A) \<Longrightarrow> B \<noteq> {} \<Longrightarrow> bdd_below (f`B) \<Longrightarrow> INFIMUM (A \<union> B) f = inf (INFIMUM A f) (INFIMUM B f)"
  using cInf_union_distrib [of "f ` A" "f ` B"] by (simp add: image_Un [symmetric])

lemma cSup_union_distrib: "A \<noteq> {} \<Longrightarrow> bdd_above A \<Longrightarrow> B \<noteq> {} \<Longrightarrow> bdd_above B \<Longrightarrow> Sup (A \<union> B) = sup (Sup A) (Sup B)"
  by (intro antisym le_supI cSup_least cSup_upper) (auto intro: le_supI1 le_supI2 cSup_upper)

lemma cSUP_union: "A \<noteq> {} \<Longrightarrow> bdd_above (f`A) \<Longrightarrow> B \<noteq> {} \<Longrightarrow> bdd_above (f`B) \<Longrightarrow> SUPREMUM (A \<union> B) f = sup (SUPREMUM A f) (SUPREMUM B f)"
  using cSup_union_distrib [of "f ` A" "f ` B"] by (simp add: image_Un [symmetric])

lemma cINF_inf_distrib: "A \<noteq> {} \<Longrightarrow> bdd_below (f`A) \<Longrightarrow> bdd_below (g`A) \<Longrightarrow> inf (INFIMUM A f) (INFIMUM A g) = (INF a:A. inf (f a) (g a))"
  by (intro antisym le_infI cINF_greatest cINF_lower2)
     (auto intro: le_infI1 le_infI2 cINF_greatest cINF_lower le_infI)

lemma SUP_sup_distrib: "A \<noteq> {} \<Longrightarrow> bdd_above (f`A) \<Longrightarrow> bdd_above (g`A) \<Longrightarrow> sup (SUPREMUM A f) (SUPREMUM A g) = (SUP a:A. sup (f a) (g a))"
  by (intro antisym le_supI cSUP_least cSUP_upper2)
     (auto intro: le_supI1 le_supI2 cSUP_least cSUP_upper le_supI)

lemma cInf_le_cSup:
  "A \<noteq> {} \<Longrightarrow> bdd_above A \<Longrightarrow> bdd_below A \<Longrightarrow> Inf A \<le> Sup A"
  by (auto intro!: cSup_upper2[of "SOME a. a \<in> A"] intro: someI cInf_lower)

end

instance complete_lattice \<subseteq> conditionally_complete_lattice
  by standard (auto intro: Sup_upper Sup_least Inf_lower Inf_greatest)

lemma cSup_eq:
  fixes a :: "'a :: {conditionally_complete_lattice, no_bot}"
  assumes upper: "\<And>x. x \<in> X \<Longrightarrow> x \<le> a"
  assumes least: "\<And>y. (\<And>x. x \<in> X \<Longrightarrow> x \<le> y) \<Longrightarrow> a \<le> y"
  shows "Sup X = a"
proof cases
  assume "X = {}" with lt_ex[of a] least show ?thesis by (auto simp: less_le_not_le)
qed (intro cSup_eq_non_empty assms)

lemma cInf_eq:
  fixes a :: "'a :: {conditionally_complete_lattice, no_top}"
  assumes upper: "\<And>x. x \<in> X \<Longrightarrow> a \<le> x"
  assumes least: "\<And>y. (\<And>x. x \<in> X \<Longrightarrow> y \<le> x) \<Longrightarrow> y \<le> a"
  shows "Inf X = a"
proof cases
  assume "X = {}" with gt_ex[of a] least show ?thesis by (auto simp: less_le_not_le)
qed (intro cInf_eq_non_empty assms)

class conditionally_complete_linorder = conditionally_complete_lattice + linorder
begin

lemma less_cSup_iff:
  "X \<noteq> {} \<Longrightarrow> bdd_above X \<Longrightarrow> y < Sup X \<longleftrightarrow> (\<exists>x\<in>X. y < x)"
  by (rule iffI) (metis cSup_least not_less, metis cSup_upper less_le_trans)

lemma cInf_less_iff: "X \<noteq> {} \<Longrightarrow> bdd_below X \<Longrightarrow> Inf X < y \<longleftrightarrow> (\<exists>x\<in>X. x < y)"
  by (rule iffI) (metis cInf_greatest not_less, metis cInf_lower le_less_trans)

lemma cINF_less_iff: "A \<noteq> {} \<Longrightarrow> bdd_below (f`A) \<Longrightarrow> (INF i:A. f i) < a \<longleftrightarrow> (\<exists>x\<in>A. f x < a)"
  using cInf_less_iff[of "f`A"] by auto

lemma less_cSUP_iff: "A \<noteq> {} \<Longrightarrow> bdd_above (f`A) \<Longrightarrow> a < (SUP i:A. f i) \<longleftrightarrow> (\<exists>x\<in>A. a < f x)"
  using less_cSup_iff[of "f`A"] by auto

lemma less_cSupE:
  assumes "y < Sup X" "X \<noteq> {}" obtains x where "x \<in> X" "y < x"
  by (metis cSup_least assms not_le that)

lemma less_cSupD:
  "X \<noteq> {} \<Longrightarrow> z < Sup X \<Longrightarrow> \<exists>x\<in>X. z < x"
  by (metis less_cSup_iff not_le_imp_less bdd_above_def)

lemma cInf_lessD:
  "X \<noteq> {} \<Longrightarrow> Inf X < z \<Longrightarrow> \<exists>x\<in>X. x < z"
  by (metis cInf_less_iff not_le_imp_less bdd_below_def)

lemma complete_interval:
  assumes "a < b" and "P a" and "\<not> P b"
  shows "\<exists>c. a \<le> c \<and> c \<le> b \<and> (\<forall>x. a \<le> x \<and> x < c \<longrightarrow> P x) \<and>
             (\<forall>d. (\<forall>x. a \<le> x \<and> x < d \<longrightarrow> P x) \<longrightarrow> d \<le> c)"
proof (rule exI [where x = "Sup {d. \<forall>x. a \<le> x & x < d --> P x}"], auto)
  show "a \<le> Sup {d. \<forall>c. a \<le> c \<and> c < d \<longrightarrow> P c}"
    by (rule cSup_upper, auto simp: bdd_above_def)
       (metis \<open>a < b\<close> \<open>\<not> P b\<close> linear less_le)
next
  show "Sup {d. \<forall>c. a \<le> c \<and> c < d \<longrightarrow> P c} \<le> b"
    apply (rule cSup_least)
    apply auto
    apply (metis less_le_not_le)
    apply (metis \<open>a<b\<close> \<open>~ P b\<close> linear less_le)
    done
next
  fix x
  assume x: "a \<le> x" and lt: "x < Sup {d. \<forall>c. a \<le> c \<and> c < d \<longrightarrow> P c}"
  show "P x"
    apply (rule less_cSupE [OF lt], auto)
    apply (metis less_le_not_le)
    apply (metis x)
    done
next
  fix d
    assume 0: "\<forall>x. a \<le> x \<and> x < d \<longrightarrow> P x"
    thus "d \<le> Sup {d. \<forall>c. a \<le> c \<and> c < d \<longrightarrow> P c}"
      by (rule_tac cSup_upper, auto simp: bdd_above_def)
         (metis \<open>a<b\<close> \<open>~ P b\<close> linear less_le)
qed

end

instance complete_linorder < conditionally_complete_linorder
  ..

lemma cSup_eq_Max: "finite (X::'a::conditionally_complete_linorder set) \<Longrightarrow> X \<noteq> {} \<Longrightarrow> Sup X = Max X"
  using cSup_eq_Sup_fin[of X] Sup_fin_eq_Max[of X] by simp

lemma cInf_eq_Min: "finite (X::'a::conditionally_complete_linorder set) \<Longrightarrow> X \<noteq> {} \<Longrightarrow> Inf X = Min X"
  using cInf_eq_Inf_fin[of X] Inf_fin_eq_Min[of X] by simp

lemma cSup_lessThan[simp]: "Sup {..<x::'a::{conditionally_complete_linorder, no_bot, dense_linorder}} = x"
  by (auto intro!: cSup_eq_non_empty intro: dense_le)

lemma cSup_greaterThanLessThan[simp]: "y < x \<Longrightarrow> Sup {y<..<x::'a::{conditionally_complete_linorder, dense_linorder}} = x"
  by (auto intro!: cSup_eq_non_empty intro: dense_le_bounded)

lemma cSup_atLeastLessThan[simp]: "y < x \<Longrightarrow> Sup {y..<x::'a::{conditionally_complete_linorder, dense_linorder}} = x"
  by (auto intro!: cSup_eq_non_empty intro: dense_le_bounded)

lemma cInf_greaterThan[simp]: "Inf {x::'a::{conditionally_complete_linorder, no_top, dense_linorder} <..} = x"
  by (auto intro!: cInf_eq_non_empty intro: dense_ge)

lemma cInf_greaterThanAtMost[simp]: "y < x \<Longrightarrow> Inf {y<..x::'a::{conditionally_complete_linorder, dense_linorder}} = y"
  by (auto intro!: cInf_eq_non_empty intro: dense_ge_bounded)

lemma cInf_greaterThanLessThan[simp]: "y < x \<Longrightarrow> Inf {y<..<x::'a::{conditionally_complete_linorder, dense_linorder}} = y"
  by (auto intro!: cInf_eq_non_empty intro: dense_ge_bounded)

class linear_continuum = conditionally_complete_linorder + dense_linorder +
  assumes UNIV_not_singleton: "\<exists>a b::'a. a \<noteq> b"
begin

lemma ex_gt_or_lt: "\<exists>b. a < b \<or> b < a"
  by (metis UNIV_not_singleton neq_iff)

end

instantiation nat :: conditionally_complete_linorder
begin

definition "Sup (X::nat set) = Max X"
definition "Inf (X::nat set) = (LEAST n. n \<in> X)"

lemma bdd_above_nat: "bdd_above X \<longleftrightarrow> finite (X::nat set)"
proof
  assume "bdd_above X"
  then obtain z where "X \<subseteq> {.. z}"
    by (auto simp: bdd_above_def)
  then show "finite X"
    by (rule finite_subset) simp
qed simp

instance
proof
  fix x :: nat
  fix X :: "nat set"
  show "Inf X \<le> x" if "x \<in> X" "bdd_below X"
    using that by (simp add: Inf_nat_def Least_le)
  show "x \<le> Inf X" if "X \<noteq> {}" "\<And>y. y \<in> X \<Longrightarrow> x \<le> y"
    using that unfolding Inf_nat_def ex_in_conv[symmetric] by (rule LeastI2_ex)
  show "x \<le> Sup X" if "x \<in> X" "bdd_above X"
    using that by (simp add: Sup_nat_def bdd_above_nat)
  show "Sup X \<le> x" if "X \<noteq> {}" "\<And>y. y \<in> X \<Longrightarrow> y \<le> x"
  proof -
    from that have "bdd_above X"
      by (auto simp: bdd_above_def)
    with that show ?thesis
      by (simp add: Sup_nat_def bdd_above_nat)
  qed
qed

end

instantiation int :: conditionally_complete_linorder
begin

definition "Sup (X::int set) = (THE x. x \<in> X \<and> (\<forall>y\<in>X. y \<le> x))"
definition "Inf (X::int set) = - (Sup (uminus ` X))"

instance
proof
  { fix x :: int and X :: "int set" assume "X \<noteq> {}" "bdd_above X"
    then obtain x y where "X \<subseteq> {..y}" "x \<in> X"
      by (auto simp: bdd_above_def)
    then have *: "finite (X \<inter> {x..y})" "X \<inter> {x..y} \<noteq> {}" and "x \<le> y"
      by (auto simp: subset_eq)
    have "\<exists>!x\<in>X. (\<forall>y\<in>X. y \<le> x)"
    proof
      { fix z assume "z \<in> X"
        have "z \<le> Max (X \<inter> {x..y})"
        proof cases
          assume "x \<le> z" with \<open>z \<in> X\<close> \<open>X \<subseteq> {..y}\<close> *(1) show ?thesis
            by (auto intro!: Max_ge)
        next
          assume "\<not> x \<le> z"
          then have "z < x" by simp
          also have "x \<le> Max (X \<inter> {x..y})"
            using \<open>x \<in> X\<close> *(1) \<open>x \<le> y\<close> by (intro Max_ge) auto
          finally show ?thesis by simp
        qed }
      note le = this
      with Max_in[OF *] show ex: "Max (X \<inter> {x..y}) \<in> X \<and> (\<forall>z\<in>X. z \<le> Max (X \<inter> {x..y}))" by auto

      fix z assume *: "z \<in> X \<and> (\<forall>y\<in>X. y \<le> z)"
      with le have "z \<le> Max (X \<inter> {x..y})"
        by auto
      moreover have "Max (X \<inter> {x..y}) \<le> z"
        using * ex by auto
      ultimately show "z = Max (X \<inter> {x..y})"
        by auto
    qed
    then have "Sup X \<in> X \<and> (\<forall>y\<in>X. y \<le> Sup X)"
      unfolding Sup_int_def by (rule theI') }
  note Sup_int = this

  { fix x :: int and X :: "int set" assume "x \<in> X" "bdd_above X" then show "x \<le> Sup X"
      using Sup_int[of X] by auto }
  note le_Sup = this
  { fix x :: int and X :: "int set" assume "X \<noteq> {}" "\<And>y. y \<in> X \<Longrightarrow> y \<le> x" then show "Sup X \<le> x"
      using Sup_int[of X] by (auto simp: bdd_above_def) }
  note Sup_le = this

  { fix x :: int and X :: "int set" assume "x \<in> X" "bdd_below X" then show "Inf X \<le> x"
      using le_Sup[of "-x" "uminus ` X"] by (auto simp: Inf_int_def) }
  { fix x :: int and X :: "int set" assume "X \<noteq> {}" "\<And>y. y \<in> X \<Longrightarrow> x \<le> y" then show "x \<le> Inf X"
      using Sup_le[of "uminus ` X" "-x"] by (force simp: Inf_int_def) }
qed
end

lemma interval_cases:
  fixes S :: "'a :: conditionally_complete_linorder set"
  assumes ivl: "\<And>a b x. a \<in> S \<Longrightarrow> b \<in> S \<Longrightarrow> a \<le> x \<Longrightarrow> x \<le> b \<Longrightarrow> x \<in> S"
  shows "\<exists>a b. S = {} \<or>
    S = UNIV \<or>
    S = {..<b} \<or>
    S = {..b} \<or>
    S = {a<..} \<or>
    S = {a..} \<or>
    S = {a<..<b} \<or>
    S = {a<..b} \<or>
    S = {a..<b} \<or>
    S = {a..b}"
proof -
  define lower upper where "lower = {x. \<exists>s\<in>S. s \<le> x}" and "upper = {x. \<exists>s\<in>S. x \<le> s}"
  with ivl have "S = lower \<inter> upper"
    by auto
  moreover
  have "\<exists>a. upper = UNIV \<or> upper = {} \<or> upper = {.. a} \<or> upper = {..< a}"
  proof cases
    assume *: "bdd_above S \<and> S \<noteq> {}"
    from * have "upper \<subseteq> {.. Sup S}"
      by (auto simp: upper_def intro: cSup_upper2)
    moreover from * have "{..< Sup S} \<subseteq> upper"
      by (force simp add: less_cSup_iff upper_def subset_eq Ball_def)
    ultimately have "upper = {.. Sup S} \<or> upper = {..< Sup S}"
      unfolding ivl_disj_un(2)[symmetric] by auto
    then show ?thesis by auto
  next
    assume "\<not> (bdd_above S \<and> S \<noteq> {})"
    then have "upper = UNIV \<or> upper = {}"
      by (auto simp: upper_def bdd_above_def not_le dest: less_imp_le)
    then show ?thesis
      by auto
  qed
  moreover
  have "\<exists>b. lower = UNIV \<or> lower = {} \<or> lower = {b ..} \<or> lower = {b <..}"
  proof cases
    assume *: "bdd_below S \<and> S \<noteq> {}"
    from * have "lower \<subseteq> {Inf S ..}"
      by (auto simp: lower_def intro: cInf_lower2)
    moreover from * have "{Inf S <..} \<subseteq> lower"
      by (force simp add: cInf_less_iff lower_def subset_eq Ball_def)
    ultimately have "lower = {Inf S ..} \<or> lower = {Inf S <..}"
      unfolding ivl_disj_un(1)[symmetric] by auto
    then show ?thesis by auto
  next
    assume "\<not> (bdd_below S \<and> S \<noteq> {})"
    then have "lower = UNIV \<or> lower = {}"
      by (auto simp: lower_def bdd_below_def not_le dest: less_imp_le)
    then show ?thesis
      by auto
  qed
  ultimately show ?thesis
    unfolding greaterThanAtMost_def greaterThanLessThan_def atLeastAtMost_def atLeastLessThan_def
    by (metis inf_bot_left inf_bot_right inf_top.left_neutral inf_top.right_neutral)
qed

lemma cSUP_eq_cINF_D:
  fixes f :: "_ \<Rightarrow> 'b::conditionally_complete_lattice"
  assumes eq: "(SUP x:A. f x) = (INF x:A. f x)"
     and bdd: "bdd_above (f ` A)" "bdd_below (f ` A)"
     and a: "a \<in> A"
  shows "f a = (INF x:A. f x)"
apply (rule antisym)
using a bdd
apply (auto simp: cINF_lower)
apply (metis eq cSUP_upper)
done

lemma cSUP_UNION:
  fixes f :: "_ \<Rightarrow> 'b::conditionally_complete_lattice"
  assumes ne: "A \<noteq> {}" "\<And>x. x \<in> A \<Longrightarrow> B(x) \<noteq> {}"
      and bdd_UN: "bdd_above (\<Union>x\<in>A. f ` B x)"
  shows "(SUP z : \<Union>x\<in>A. B x. f z) = (SUP x:A. SUP z:B x. f z)"
proof -
  have bdd: "\<And>x. x \<in> A \<Longrightarrow> bdd_above (f ` B x)"
    using bdd_UN by (meson UN_upper bdd_above_mono)
  obtain M where "\<And>x y. x \<in> A \<Longrightarrow> y \<in> B(x) \<Longrightarrow> f y \<le> M"
    using bdd_UN by (auto simp: bdd_above_def)
  then have bdd2: "bdd_above ((\<lambda>x. SUP z:B x. f z) ` A)"
    unfolding bdd_above_def by (force simp: bdd cSUP_le_iff ne(2))
  have "(SUP z:\<Union>x\<in>A. B x. f z) \<le> (SUP x:A. SUP z:B x. f z)"
    using assms by (fastforce simp add: intro!: cSUP_least intro: cSUP_upper2 simp: bdd2 bdd)
  moreover have "(SUP x:A. SUP z:B x. f z) \<le> (SUP z:\<Union>x\<in>A. B x. f z)"
    using assms by (fastforce simp add: intro!: cSUP_least intro: cSUP_upper simp: image_UN bdd_UN)
  ultimately show ?thesis
    by (rule order_antisym)
qed

lemma cINF_UNION:
  fixes f :: "_ \<Rightarrow> 'b::conditionally_complete_lattice"
  assumes ne: "A \<noteq> {}" "\<And>x. x \<in> A \<Longrightarrow> B(x) \<noteq> {}"
      and bdd_UN: "bdd_below (\<Union>x\<in>A. f ` B x)"
  shows "(INF z : \<Union>x\<in>A. B x. f z) = (INF x:A. INF z:B x. f z)"
proof -
  have bdd: "\<And>x. x \<in> A \<Longrightarrow> bdd_below (f ` B x)"
    using bdd_UN by (meson UN_upper bdd_below_mono)
  obtain M where "\<And>x y. x \<in> A \<Longrightarrow> y \<in> B(x) \<Longrightarrow> f y \<ge> M"
    using bdd_UN by (auto simp: bdd_below_def)
  then have bdd2: "bdd_below ((\<lambda>x. INF z:B x. f z) ` A)"
    unfolding bdd_below_def by (force simp: bdd le_cINF_iff ne(2))
  have "(INF z:\<Union>x\<in>A. B x. f z) \<le> (INF x:A. INF z:B x. f z)"
    using assms by (fastforce simp add: intro!: cINF_greatest intro: cINF_lower simp: bdd2 bdd)
  moreover have "(INF x:A. INF z:B x. f z) \<le> (INF z:\<Union>x\<in>A. B x. f z)"
    using assms  by (fastforce simp add: intro!: cINF_greatest intro: cINF_lower2  simp: bdd bdd_UN bdd2)
  ultimately show ?thesis
    by (rule order_antisym)
qed

lemma cSup_abs_le:
  fixes S :: "('a::{linordered_idom,conditionally_complete_linorder}) set"
  shows "S \<noteq> {} \<Longrightarrow> (\<And>x. x\<in>S \<Longrightarrow> \<bar>x\<bar> \<le> a) \<Longrightarrow> \<bar>Sup S\<bar> \<le> a"
  apply (auto simp add: abs_le_iff intro: cSup_least)
  by (metis bdd_aboveI cSup_upper neg_le_iff_le order_trans)

end


chapter \<open>Code Snippets\<close>
theory Snippets
imports "lib/VTcomp"
begin

  section \<open>Find Element in Array (Arrays)\<close>

  definition "find_elem (x::int) xs \<equiv> doN {
    WHILEIT (\<lambda>i. i\<le>length xs \<and> x\<notin>set (take i xs)) (\<lambda>i. i<length xs \<and> xs!i\<noteq>x) (\<lambda>i. RETURN (i+1)) 0
  }"

  lemma find_elem_correct: "find_elem x xs \<le> SPEC (\<lambda>i. i\<le>length xs \<and> (i<length xs \<longrightarrow> xs!i = x))"
    unfolding find_elem_def
    apply refine_vcg
    apply (rule wf_measure[of "\<lambda>i. length xs - i"])
    apply (auto simp: in_set_conv_nth)
    (*sledgehammer*)
    using less_Suc_eq by blast

  sepref_definition find_elem_impl is "uncurry find_elem" :: "int_assn\<^sup>k *\<^sub>a (array_assn int_assn)\<^sup>k \<rightarrow>\<^sub>a nat_assn"
    unfolding find_elem_def short_circuit_conv
    by sepref

  export_code find_elem_impl in Haskell module_name test

  subsection \<open>Combined Correctness Theorem\<close>
  lemma find_elem_r1: "(find_elem, \<lambda> x xs. SPEC (\<lambda>i. i\<le>length xs \<and> (i<length xs \<longrightarrow> xs!i = x))) \<in> Id \<rightarrow> Id \<rightarrow> \<langle>Id\<rangle>nres_rel"
    using find_elem_correct by (auto intro: nres_relI)

  thm find_elem_impl.refine[FCOMP find_elem_r1]

  section \<open>Check Prefix (Arrays, Exceptions: Check)\<close>

  definition "check_prefix xs ys \<equiv> doE {
    CHECK (length xs \<le> length ys) ();
    EWHILEIT (\<lambda>i. i\<le>length xs \<and> take i xs = take i ys) (\<lambda>i. i<length xs) (\<lambda>i. doE {
      EASSERT (i<length xs \<and> i<length ys);
      CHECK (xs!i = ys!i) ();
      ERETURN (i+1)
    } ) 0;
    ERETURN ()
  }"

  (* ESPEC Exc Normal ! *)
  lemma check_prefix_correct: "check_prefix xs ys \<le> ESPEC (\<lambda>_. xs \<noteq> take (length xs) ys) (\<lambda>_. xs = take (length xs) ys)"
    unfolding check_prefix_def
    apply (refine_vcg EWHILEIT_rule[where R="measure (\<lambda>i. length xs - i)"])
    apply auto []
    apply auto []
    apply auto []
    apply auto []
    apply auto []
    apply auto []
    subgoal
      by (simp add: take_Suc_conv_app_nth)
    apply auto []
    apply auto []
    subgoal
      by (metis nth_take)
    subgoal
      by force
    apply auto []
    done

  synth_definition check_prefix_bd is [enres_unfolds]: "check_prefix xs ys = \<hole>"
    apply (rule CNV_eqD)
    unfolding check_prefix_def
    apply opt_enres_unfold
    apply (rule CNV_I)
    done

  sepref_definition check_prefix_impl is "uncurry check_prefix_bd"
    :: "(array_assn int_assn)\<^sup>k *\<^sub>a (array_assn int_assn)\<^sup>k \<rightarrow>\<^sub>a (unit_assn +\<^sub>a unit_assn)"
    unfolding check_prefix_bd_def
    by sepref

  export_code check_prefix_impl checking SML_imp

  subsection \<open>Modularity\<close>

  lemmas [refine_vcg] = check_prefix_correct[THEN ESPEC_trans]
  thm SPEC_trans (* for plain nres-monad without exceptions *)

  (* TODO: I remember to have automated the order_trans transformation, but cannot find it right now. *)

  definition "is_prefix' xs ys \<equiv> CATCH (doE {check_prefix xs ys; ERETURN True }) (\<lambda>_. ERETURN False)"

  lemma is_prefix'_correct: "is_prefix' xs ys \<le> ESPEC (\<lambda>_. False) (\<lambda>r. r \<longleftrightarrow> xs = take (length xs) ys)"
    unfolding is_prefix'_def
    apply refine_vcg
    by auto

  lemmas [sepref_fr_rules] = check_prefix_impl.refine
  sepref_register check_prefix_bd :: "'a list \<Rightarrow> 'a list \<Rightarrow> (unit+unit) nres"
    (* Optional interface type. Required if interfaces used that do not match Isabelle types, e.g. i_map, i_mtx, \<dots>*)

  synth_definition is_prefix_bd' is [enres_unfolds]: "is_prefix' xs ys = \<hole>"
    apply (rule CNV_eqD)
    unfolding is_prefix'_def
    apply opt_enres_unfold
    apply (rule CNV_I)
    done

  sepref_definition is_prefix_impl' is "uncurry is_prefix_bd'"
    :: "(array_assn int_assn)\<^sup>k *\<^sub>a (array_assn int_assn)\<^sup>k \<rightarrow>\<^sub>a (unit_assn +\<^sub>a bool_assn)"
    unfolding is_prefix_bd'_def
    by sepref

  export_code is_prefix_impl' checking SML_imp

  section \<open>Is Prefix (Arrays, Exceptions: Catch)\<close>

  definition "is_prefix xs ys \<equiv> CATCH (doE {
    CHECK (length xs \<le> length ys) False;
    EWHILEIT (\<lambda>i. i\<le>length xs \<and> take i xs = take i ys) (\<lambda>i. i<length xs) (\<lambda>i. doE {
      EASSERT (i<length xs \<and> i<length ys);
      CHECK (xs!i = ys!i) False;
      ERETURN (i+1)
    } ) 0;
    THROW True
  }) (ERETURN)"

  (* ESPEC Exc Normal ! *)
  lemma "is_prefix xs ys \<le> ESPEC (\<lambda>_. False) (\<lambda>r. r \<longleftrightarrow> xs = take (length xs) ys)"
    unfolding is_prefix_def
    apply (refine_vcg EWHILEIT_rule[where R="measure (\<lambda>i. length xs - i)"])
    apply auto []
    apply auto []
    apply auto []
    apply auto []
    apply auto []
    apply auto []
    subgoal
      by (simp add: take_Suc_conv_app_nth)
    apply auto []
    apply auto []
    subgoal
      by (metis nth_take)
    subgoal
      by force
    apply auto []
    done

  synth_definition is_prefix_bd is [enres_unfolds]: "is_prefix xs ys = \<hole>"
    apply (rule CNV_eqD)
    unfolding is_prefix_def
    apply opt_enres_unfold
    apply (rule CNV_I)
    done

  sepref_definition is_prefix_impl is "uncurry is_prefix_bd"
    :: "(array_assn int_assn)\<^sup>k *\<^sub>a (array_assn int_assn)\<^sup>k \<rightarrow>\<^sub>a (unit_assn +\<^sub>a bool_assn)"
    unfolding is_prefix_bd_def
    by sepref

  export_code is_prefix_impl checking SML_imp

  section \<open>Copy Array (Arrays, For i=l..u)\<close>

  definition "cp_array xs \<equiv> doN {
    let ys = op_array_replicate (length xs) 0;   \<comment> \<open>Use proper constructors\<close>

    ys \<leftarrow> nfoldli [0..<length xs] (\<lambda>_. True) (\<lambda>i ys. doN {  \<comment> \<open>Ensure linearity! \<open>ys\<leftarrow>\<dots>\<close>\<close>
      ASSERT (i<length xs \<and> i<length ys);
      RETURN (ys[i:=xs!i])
    }) ys;

    RETURN ys
  }"

  lemma "cp_array xs \<le> SPEC (\<lambda>ys. ys=xs)"
    unfolding cp_array_def
    supply nfoldli_rule nfoldli_rule[where I="\<lambda>l1 l2 ys. length ys = length xs \<and> (\<forall>i\<in>set l1. ys!i = xs!i)", refine_vcg]
    apply refine_vcg
    apply auto
    subgoal
      using upt_eq_lel_conv by blast
    subgoal
      using upt_eq_lel_conv by blast
    subgoal
      by (simp add: nth_list_update)
    subgoal
      by (simp add: nth_equalityI)
    done

  term arl_assn

  subsection \<open>Proof with \<open>nfoldli_upt_rule\<close>\<close>
  lemma "cp_array xs \<le> SPEC (\<lambda>ys. ys=xs)"
    unfolding cp_array_def
    supply nfoldli_upt_rule nfoldli_upt_rule[where I="\<lambda>i ys. length ys = length xs \<and> (\<forall>j<i. ys!j = xs!j)", refine_vcg]
    apply refine_vcg
    apply auto
    subgoal
      using less_Suc_eq by auto
    subgoal
      by (simp add: nth_equalityI)
    done

  sepref_definition cp_array_impl is cp_array :: "(array_assn nat_assn)\<^sup>k \<rightarrow>\<^sub>a array_assn nat_assn"
    unfolding cp_array_def
    by sepref

end


theory Mergeable_Roalist imports "../Lib/Oalist/Roalist" "Mergeable_Oalist" "Pord" "Mergeable_Instances"
begin

(*
 * This file contains mergeable instances for RAlist - a variant of AList representing a
 * recursive key-value store (i.e., values can themselves be key-value stores).
 * Note that several key theorems are admitted ("sorry") here, rather than being proven.
 * This is because the proofs became extremely tedious; however, we do believe they are
 * provable.
 *)

lift_definition roalist_leq :: "('key :: linorder, 'value :: Pord, 'd :: Pord) roalist \<Rightarrow> ('key, 'value, 'd :: Pord) roalist \<Rightarrow> bool"
is "list_leq :: ('key :: linorder, 'value :: Pord, 'd option) roalist' \<Rightarrow>
                ('key, 'value, 'd option) roalist' \<Rightarrow> bool" .

(* copied and edited proofs from MergeableAList. *)
lemma list_leq_refl :
  assumes H : "strict_order (map fst a)"
  shows "list_leq a a" using H
proof(induction a)
  case Nil
  then show ?case by auto
next
  case (Cons a1 a2)
  obtain a1k a1v where A1 : "a1 = (a1k, a1v)" by(cases a1; auto)
  have SO : "strict_order (map fst a2)" using Cons strict_order_tl A1 by auto
  have D : "distinct (map fst (a1#a2))" using strict_order_distinct[OF Cons.prems] by auto
  hence Notin : "a1k \<notin> set (map fst a2)" using A1 by auto
  then show ?case using list_leq_cons[OF Cons.IH[OF SO]] A1 by(auto simp add:leq_refl)
qed

lemma list_leq_trans :
  assumes HO1 : "strict_order (map fst l1)"
  assumes HO2 : "strict_order (map fst l2)"
  assumes HO3 : "strict_order (map fst l3)"
  assumes H1 : "list_leq l1 l2"
  assumes H2 : "list_leq l2 l3"
  shows "list_leq l1 l3" using assms
proof(induction l1 arbitrary: l2 l3)
  case Nil
  then show ?case by auto
next
  case (Cons l1h l1t)
  obtain a1k and a1v where Ha : "l1h = (a1k, a1v)" by(cases l1h; auto)
  hence Hleq12 : "list_leq l1t l2"  using Cons
    by(auto split:option.splits)
  obtain a2v where Ha2v : "(a1k, a2v) \<in> set l2" and Ha2vl:  "a1v <[ a2v"
    using Ha Cons strict_order_distinct[of "a1k # map fst l1t"]
          map_of_SomeD [of l2 a1k]
    by(auto split:option.splits)
  obtain a3v where Ha3v : "(a1k, a3v) \<in> set l3" and Ha3vl : "a2v <[ a3v"
    using Cons Ha list_leqD[OF Cons.prems(5) Ha2v]
    by(auto split:option.splits)
  have Hav13 : "a1v <[ a3v" using leq_trans[OF Ha2vl Ha3vl] by auto
  have sto1 : "strict_order (map fst l1t)" using strict_order_tl[of a1k "map fst l1t"] Ha Cons by(auto)
  show "list_leq (l1h # l1t) l3" using Ha Ha3v Hav13
    map_of_is_SomeI[OF strict_order_distinct[OF Cons.prems(3)]]
      Cons.IH[OF sto1 Cons.prems(2) Cons.prems(3) Hleq12]
      Cons.prems
    by auto
qed

lemma list_leq_antisym :
  assumes Hord1 : "strict_order (map fst l1)"
  assumes Hord2 : "strict_order (map fst l2)"
  assumes Hleq1 : "list_leq l1 l2"
  assumes Hleq2 : "list_leq l2 l1"
  shows "l1 = l2"
proof-
  have Conc' : "set l1 = set l2"
  proof(rule Set.equalityI; rule Set.subsetI)
    fix x :: "('a * 'b)"
    obtain xk and xv where Hx: "x = (xk, xv)" by(cases x; auto)
    assume H : "x \<in> set l1"
    hence H' : "(xk, xv) \<in> set l1" using Hx by auto
    obtain v' where  Elv' : "(xk, v') \<in> set l2" and Leqv' : "xv <[ v'" using list_leqD[OF (*Hord1 Hord2*) Hleq1 H'] by auto
    obtain v'' where Elv'' : "(xk, v'') \<in> set l1" and Leqv'' : "v' <[ v''" using list_leqD[OF (*Hord2 Hord1*) Hleq2 Elv'] by auto
    have Hord1_d : "distinct (map fst l1)" using strict_order_distinct[OF Hord1] by auto
    have H'' : "xk \<in> set (map fst l1)" using H' imageI[OF H', of fst] by(auto)
    obtain i1 where Hi11 : "i1 < length l1" and Hi12 : "l1 ! i1 = (xk, xv)" using H' List.in_set_conv_nth[of "(xk, xv)" "l1"] by auto
    obtain i1' where Hi1'1 : "i1' < length l1" and Hi1'2 :  "l1 ! i1' = (xk, v'')" using Elv'' List.in_set_conv_nth[of "(xk, v'')" "l1"]
      by(auto)
    have "i1 = i1'" using Hi11 Hi12 Hi1'1 Hi1'2 List.distinct_Ex1[OF Hord1_d H''] by(auto)
    hence "v'' = xv" using Hi12 Hi1'2 by auto
    hence Leqv'2 : "v' <[ xv" using Leqv'' by auto
    hence "xv = v'" using leq_antisym[OF Leqv' Leqv'2] by auto
    thus "x \<in> set l2" using Elv' Hx by auto
  next
    fix x :: "('a * 'b)"
    obtain xk and xv where Hx: "x = (xk, xv)" by(cases x; auto)
    assume H : "x \<in> set l2"
    hence H' : "(xk, xv) \<in> set l2" using Hx by auto
    obtain v' where  Elv' : "(xk, v') \<in> set l1" and Leqv' : "xv <[ v'" using list_leqD[OF Hleq2 H'] by auto
    obtain v'' where Elv'' : "(xk, v'') \<in> set l2" and Leqv'' : "v' <[ v''" using list_leqD[OF Hleq1 Elv'] by auto
    have Hord1_d : "distinct (map fst l2)" using strict_order_distinct[OF Hord2] by auto
    have H'' : "xk \<in> set (map fst l2)" using H' imageI[OF H', of fst] by(auto)
    obtain i1 where Hi11 : "i1 < length l2" and Hi12 : "l2 ! i1 = (xk, xv)" using H' List.in_set_conv_nth[of "(xk, xv)" "l2"] by auto
    obtain i1' where Hi1'1 : "i1' < length l2" and Hi1'2 :  "l2 ! i1' = (xk, v'')" using Elv'' List.in_set_conv_nth[of "(xk, v'')" "l2"]
      by(auto)
    have "i1 = i1'" using Hi11 Hi12 Hi1'1 Hi1'2 List.distinct_Ex1[OF Hord1_d H''] by(auto)
    hence "v'' = xv" using Hi12 Hi1'2 by auto
    hence Leqv'2 : "v' <[ xv" using Leqv'' by auto
    hence "xv = v'" using leq_antisym[OF Leqv' Leqv'2] by auto
    thus "x \<in> set l1" using Elv' Hx by auto
  qed

  show "l1 = l2"  using strict_order_set_eq[OF Hord1 Hord2 Conc'] by auto
qed

lift_definition roa_empty :: "('k :: linorder, 'v, 'd) roalist"
is "[([], Inr None)] :: ('k, 'v, 'd option) roalist'"
  by(auto simp add: strict_order_def roalist_valid_def)

value "roalist_get (roa_empty :: (String.literal, unit, unit) roalist) (String.implode ''a'') "

fun roa_make_vs :: "('k :: linorder  * 'v) list \<Rightarrow> ('k, 'v, 'd) roalist" where
"roa_make_vs [] = roa_empty"
| "roa_make_vs ((kh, vh)#t) =
    roalist_update_v kh vh (roa_make_vs t)"

instantiation roalist :: (linorder, Pord, Pord) Pord
begin

definition pleq_roalist :
"pleq l1 l2 = roalist_leq l1 l2"
instance sorry
(*
  fix l1 :: "('a :: linorder, 'b :: Pord, 'c :: pord) roalist"
  show "l1 <[ l1" unfolding pleq_roalist
    by(transfer; auto simp add: list_leq_refl)
next
  fix l1 l2 l3 :: "('a :: linorder, 'b :: Pord) roalist"
  assume H1 : "l1 <[ l2"
  assume H2 : "l2 <[ l3"
  show "l1 <[ l3" using H1 H2 unfolding pleq_roalist
  proof(transfer)
    fix l1 l2 l3 :: "('a, 'b) roalist'"
    assume HO1 : "strict_order (map fst l1) \<and> roalist_valid l1"
    assume HO2 : "strict_order (map fst l2) \<and> roalist_valid l2"
    assume HO3 : "strict_order (map fst l3) \<and> roalist_valid l3"
    assume H1 : "list_leq l1 l2"
    assume H2 : "list_leq l2 l3"
    show "list_leq l1 l3" using list_leq_trans[of l1 l2 l3] HO1 HO2 HO3 H1 H2 by auto
  qed
next
  fix l1 l2 :: "('a :: linorder, 'b :: Pord) roalist"
  assume H1 : "l1 <[ l2"
  assume H2 : "l2 <[ l1"
  show "l1 = l2" using H1 H2 unfolding pleq_roalist
  proof(transfer)
    fix l1 l2 :: "('a, 'b) roalist'"
    assume HO1 : "strict_order (map fst l1) \<and> roalist_valid l1"
    assume HO2 : "strict_order (map fst l2) \<and> roalist_valid l2"
    assume H1 : "list_leq l1 l2"
    assume H2 : "list_leq l2 l1"
    show "l1 = l2" using list_leq_antisym HO1 HO2 H1 H2 by auto
  qed
qed
*)
end

(*
lemma roalist_valid_hd :
  assumes H1 : "strict_order (map fst l)"
  assumes H2 : "roalist_valid l"
  shows "\<exists> l' . l = ([], Inr ())#l'"
proof(cases l)
  case Nil
  then show ?thesis using H2 by(auto simp add:roalist_valid_def)
next
  case (Cons a l')
  then obtain ak av where Ha : "a = (ak, av)" by(cases a; auto)
  then show ?thesis
  proof(cases "ak = []")
    case True
    have In1 : "([], Inr ()) \<in> set l" using map_of_SomeD[OF roalist_valid_elim1[OF H2]] by auto
    have In2 : "([], av) \<in>  set l" using Ha Cons True by auto
    hence "av = Inr ()" using imageI[OF In1, of fst] distinct_unique_value[OF strict_order_distinct[OF H1] In1 In2]  by(auto)
    then show ?thesis using Ha Cons True by auto
  next
    case False
    have In1 : "([], Inr ()) \<in> set l" using map_of_SomeD[OF roalist_valid_elim1[OF H2]] by auto
    hence In1' : "([], Inr ()) \<in> set l'" using Cons False Ha by auto
    then obtain ix where "ix < length l'" "l' ! ix = ([], Inr ())" unfolding in_set_conv_nth by auto
    hence Bad : "ak < []" using strict_order_unfold[OF H1, of "1 + ix" 0] H1 Cons Ha by(auto)
    hence False using False unfolding list_lo_lt by(cases ak; auto)
    then show ?thesis by auto
  qed
qed

lemma roalist_delete_clos'_order :
  assumes H : "strict_order (map fst list)"
  shows "strict_order (map fst (roalist_delete_clos' k list))" using H
proof(induction list)
  case Nil
  then show ?case by(auto intro: strict_order_nil)
next
  case (Cons a list)
  obtain kh vh where A : "a = (kh, vh)" by (cases a; auto)
  show ?case
  proof(cases kh)
    assume Nil' : "kh = []"
    then show ?thesis
    proof(cases "map fst (roalist_delete_clos' k list)")
      assume Nil'' : "map fst (roalist_delete_clos' k list) = []"
      then show ?thesis
        using Cons Nil' strict_order_tl A strict_order_singleton strict_order_cons
        by(auto)
    next
      fix h' t'
      assume Cons'' : "map fst (roalist_delete_clos' k list) = (h'#t')"
      then have A2_in' : "h' \<in> set (map fst (roalist_delete_clos' k list))" by auto
      then obtain v' where V'_in : "(h', v') \<in> set (roalist_delete_clos' k list)"
        by(auto)
      have Ord' : "strict_order (map fst list)" using strict_order_tl Cons.prems by auto
      have A2_in_orig : "(h', v') \<in> set list"
        using Cons roalist_delete_clos'_elem[OF Ord' V'_in] by auto
      then obtain a2idx where "a2idx < length list" "list ! a2idx = (h', v')"
        by (auto simp add: List.in_set_conv_nth)
      hence Conc_hd : "[] < h'" using strict_order_unfold[OF Cons.prems(1), of "1 + a2idx" 0] Cons A Nil'
        by(auto simp add: list_lo_lt)
      then show ?thesis using Cons Nil' A Cons'' strict_order_cons[of "[]" h'] Ord'
        by(auto)
    qed
  next
    fix khh kht
    assume Cons' : "kh = khh#kht"
    then show ?thesis
    proof(cases "map fst (roalist_delete_clos' k list)")
      assume Nil'' : "map fst (roalist_delete_clos' k list) = []"
      then show ?thesis
        using Cons Cons' strict_order_tl A strict_order_singleton strict_order_cons
        by(auto)
    next
      fix h' t'
      assume Cons'' : "map fst (roalist_delete_clos' k list) = (h'#t')"
      then have A2_in' : "h' \<in> set (map fst (roalist_delete_clos' k list))" by auto
      then obtain v' where V'_in : "(h', v') \<in> set (roalist_delete_clos' k list)"
        by(auto)
      have Ord' : "strict_order (map fst list)" using strict_order_tl Cons.prems by auto
      have A2_in_orig : "(h', v') \<in> set list"
        using Cons roalist_delete_clos'_elem[OF Ord' V'_in] by auto
      then obtain a2idx where "a2idx < length list" "list ! a2idx = (h', v')"
        by (auto simp add: List.in_set_conv_nth)
      hence Conc_hd : "kh < h'" using strict_order_unfold[OF Cons.prems(1), of "1 + a2idx" 0] Cons A Cons'
        by(auto simp add: list_lo_lt)
      then show ?thesis using Cons Cons' A Cons'' strict_order_cons[of "kh" h'] Ord'
        by(auto)
    qed
  qed
qed
*)
(* need to factor out second lemma here *)
lift_definition roalist_delete_clos :: "('k :: linorder) \<Rightarrow> ('k :: linorder, 'v, 'd) roalist \<Rightarrow> ('k, 'v, 'd) roalist"
is roalist_delete_clos' sorry
(*
proof-
  fix k :: "'k"
  fix list :: "('k :: linorder, 'v) roalist'"
  assume H : "strict_order (map fst list) \<and> roalist_valid list"
  hence H1 :  "strict_order (map fst list)" and H2 : "roalist_valid list" by auto

  have C1 : "strict_order (map fst (roalist_delete_clos' k list))" using roalist_delete_clos'_order[OF H1]
    by auto

  have C2 : "roalist_valid (roalist_delete_clos' k list)"
  proof(rule roalist_valid_intro)
    show "map_of (roalist_delete_clos' k list) [] = Some (Inr ())"
      using roalist_valid_hd[OF H1 H2] by(auto)
  next
    fix pref v sufh suf
    assume Res_in : "map_of (roalist_delete_clos' k list) pref = Some (Inl v)"
    have Res_in' : "(pref, Inl v) \<in> set (roalist_delete_clos' k list)" using map_of_SomeD[OF Res_in] by auto
    have Orig_in' : "(pref, Inl v) \<in> set list" using roalist_delete_clos'_elem[OF H1 Res_in'] by auto
    have Orig_in : "map_of list pref = Some (Inl v)" using map_of_is_SomeI[OF strict_order_distinct[OF H1] Orig_in'] by auto
    have Orig_in2 : "map_of list (pref @ sufh # suf) = None"
      using roalist_valid_elim2[OF H2 Orig_in] by auto
    obtain prefh suf' where Pref' : "pref @ sufh # suf = prefh#suf'" by(cases pref; auto)
    show "map_of (roalist_delete_clos' k list) (pref @ sufh # suf) = None"
    proof(cases "map_of (roalist_delete_clos' k list) (pref @ sufh # suf)")
      case None
      then show ?thesis by auto
    next
      case (Some bad)
      have Some' : "(prefh#suf', bad) \<in> set (roalist_delete_clos' k list)"
        using map_of_SomeD[OF Some] Pref' by auto
      have Some'_orig : "map_of list (prefh#suf') = Some bad"
        using map_of_is_SomeI[OF strict_order_distinct[OF H1] roalist_delete_clos'_elem[OF H1 Some']] by auto
      have Some'_orig' : "(prefh#suf', bad) \<in> set list"
        using map_of_SomeD[OF Some'_orig] by auto

      have False using Some'_orig Orig_in2 unfolding Pref' by auto
      thus ?thesis by auto
    qed
  next
    fix pref x sufh suf
    assume Res_in : "map_of (roalist_delete_clos' k list) (pref @ sufh # suf) = Some x"
    have Res_in' : "(pref@sufh#suf, x) \<in> set (roalist_delete_clos' k list)" using map_of_SomeD[OF Res_in] by auto
    have Orig_in' : "(pref@sufh#suf, x) \<in> set list" using roalist_delete_clos'_elem[OF H1 Res_in'] by auto
    have Orig_in : "map_of list (pref@sufh#suf) = Some x"
      using map_of_is_SomeI[OF strict_order_distinct[OF H1] Orig_in'] by auto
    have Orig_in2 : "map_of list pref = Some (Inr ())" using roalist_valid_elim3[OF H2 Orig_in] by auto
    have Orig_in2' : "(pref, Inr ()) \<in> set list"
      using map_of_SomeD[OF Orig_in2] by auto

    obtain prefh suf' where Pref' : "pref @ sufh # suf = prefh#suf'" by(cases pref; auto)

    show "map_of (roalist_delete_clos' k list) pref = Some (Inr ())"
    proof(cases "k = prefh")
      case True
      then have False using imageI[OF Res_in', of fst] roalist_delete_clos'_notelem2[OF H1, of prefh suf'] unfolding Pref'
        by(auto)
      thus ?thesis by auto
    next
      case False
      show "map_of (roalist_delete_clos' k list) pref = Some (Inr ())"
      proof(cases pref)
        case Nil
        then show ?thesis using roalist_valid_hd[OF H1 H2] by(auto)
      next
        case (Cons prefh' preft)
        hence Prefh_h' : "prefh = prefh'" using Pref' by auto
        have Conc' : "(prefh' # preft, Inr ()) \<in> set (roalist_delete_clos' k list)"
          using roalist_delete_clos'_elem_contra[OF H1, of prefh preft "Inr ()" k] Orig_in2' False
          unfolding Cons Prefh_h'
          by auto
        thus ?thesis using map_of_is_SomeI[OF strict_order_distinct[OF roalist_delete_clos'_order[OF H1]] Conc']
          unfolding Cons by auto
      qed
    qed
  qed

  show "strict_order (map fst (roalist_delete_clos' k list)) \<and> roalist_valid (roalist_delete_clos' k list)"
    using C1 C2 by auto
qed
*)

fun roalist_gather'_check ::
  "('k :: linorder, 'v, 'd) roalist' \<Rightarrow> 'k \<Rightarrow> ('k :: linorder, 'v, 'd) roalist' option" where
"roalist_gather'_check l k =
  (case map_of l [k] of
    Some (Inr _) \<Rightarrow> Some (roalist_gather' l k)
    | _ \<Rightarrow> None)"

(*
  empty list \<Rightarrow> id
  if we are a prefix, we include the result
  otherwise we don't
*)

(*
| "roalist_gathers' (([kh], (Inl _))#l) k = roalist_gathers' l k"
| "roalist_gathers' (([kh], (Inr ()))#l) k =
  ( if k = kh then ([], Inr ())#roalist_gathers' l k
    else roalist_gathers' l k)"
| "roalist_gather' (((khh1#khh2#kht), vh)#l) k =
  ( if k = khh1 then (khh2#kht, vh) # roalist_gathers' l k
    else roalist_gathers' l k)"
*)

(*
lemma roalist_gather'_correct :
  assumes H1 : "strict_order (map fst l)"
  and H2 : "roalist_valid l"
  and H3 : "roalist_gather'_check l k = Some l'"
  shows "roalist_valid l'"
proof(rule roalist_valid_intro)
  have M :  "map_of l [k] = Some (Inr ())" using H3
    by(cases "map_of l [k]"; auto split:sum.splits)

  have Lin : "([k], Inr ()) \<in> set l" using map_of_SomeD[OF M] by auto

  have Gath : "map_of (roalist_gather' l k) [] = Some (Inr ())"
    using map_of_is_SomeI[OF strict_order_distinct[OF roalist_gather'_order[OF H1]]
                             roalist_gather'_elem'2[OF H1 Lin]] by auto

  show "map_of l' [] = Some (Inr ())" using H3 M
    roalist_gather'_elem'2[OF H1 Lin] Gath
    by(auto split:unit.splits)
next
  fix pref v sufh suf
  assume H : "map_of l' pref = Some (Inl v) "
  have M :  "map_of l [k] = Some (Inr ())" using H3
    by(cases "map_of l [k]"; auto split:sum.splits)

  have H' : "(pref, Inl v) \<in> set (roalist_gather' l k)"
    using H H3 M map_of_SomeD[OF H]
    by(auto split:unit.splits)

  have H'l : "(k#pref, Inl v) \<in> set l"
    using roalist_gather'_elem[OF H1 H'] by auto

  hence Lval : "map_of l (k#pref) = Some (Inl v)"
    using map_of_is_SomeI[OF strict_order_distinct[OF H1]] by auto

  show "map_of l' (pref @ sufh # suf) = None"
  proof(cases "map_of l' (pref @ sufh # suf)")
    case None thus ?thesis by auto
  next
    case (Some bad)

    have False' : "(pref @ sufh # suf, bad) \<in> set (roalist_gather' l k)"
      using H H3 M map_of_SomeD[OF Some]
      by(auto split:unit.splits)

    have False'l : "(k#pref @ sufh # suf, bad) \<in> set l"
      using roalist_gather'_elem[OF H1 False'] by auto

    hence Lval' : "map_of l (k#pref @ sufh # suf) = Some (bad)"
      using map_of_is_SomeI[OF strict_order_distinct[OF H1]] by auto

    have "map_of l ((k#pref) @ sufh # suf) = None"
      using roalist_valid_elim2[OF H2 Lval] by auto

    hence False using Lval' by auto
    thus ?thesis by auto
  qed
next
  fix pref x sufh suf
  assume H : "map_of l' (pref @ sufh # suf) = Some x"
  have M :  "map_of l [k] = Some (Inr ())" using H3
    by(cases "map_of l [k]"; auto split:sum.splits)

  have H' : "(pref@ sufh # suf, x) \<in> set (roalist_gather' l k)"
    using H H3 M map_of_SomeD[OF H]
    by(auto split:unit.splits)

  have H'l : "(k#pref @ sufh # suf, x) \<in> set l"
    using roalist_gather'_elem[OF H1 H'] by auto

  hence Lval : "map_of l (k#pref @ sufh # suf) = Some (x)"
    using map_of_is_SomeI[OF strict_order_distinct[OF H1]] by auto

  have Lval' : "map_of l (k#pref) = Some (Inr ())"
    using roalist_valid_elim3[OF H2] Lval by(auto)

  have Prefl : "(k#pref, Inr ()) \<in> set l"
    using map_of_SomeD[OF Lval'] by auto

  have Prefl_l' : "(pref, Inr ()) \<in> set (roalist_gather' l k)"
    using roalist_gather'_elem'2[OF H1 Prefl] by auto

  hence Gath : "map_of (roalist_gather' l k) pref = Some (Inr ())"
    using map_of_is_SomeI[OF strict_order_distinct[OF roalist_gather'_order[OF H1]] Prefl_l']
    by auto

  show "map_of l' pref = Some (Inr ())"
    using H3 M Gath by(auto split:unit.splits)
qed
*)

lift_definition roalist_gather :: "('k :: linorder, 'v, 'd) roalist \<Rightarrow> 'k \<Rightarrow> ('k, 'v, 'd) roalist option"
is roalist_gather'_check sorry
(*
proof-
  fix k :: "'k"
  fix list :: "('k :: linorder, 'v) roalist'"
  assume H : "strict_order (map fst list) \<and> roalist_valid list"
  hence H1 : "strict_order (map fst list)" and H2 : "roalist_valid list" by auto

  have C1 : "strict_order (map fst (roalist_gather' list k))"
    using roalist_gather'_order[OF H1] by auto

  show "pred_option (\<lambda>xs. strict_order (map fst xs) \<and> roalist_valid xs)
        (roalist_gather'_check list k)"
  proof(cases "roalist_gather'_check list k")
    case None
    then show ?thesis by(auto)
  next
    case (Some a)

    have C2 : "roalist_valid a" using roalist_gather'_correct[OF H1 H2 Some] by auto
    then show ?thesis using Some C1
      by(auto split:option.split_asm sum.split_asm unit.split_asm)
  qed
qed
*)
(*
(* idea: we know we can find a sup, but we need to prove that it also
   meets roalist_valid.
   suppose UB isn't roalist_valid. then either
    - [] doesnt map to Inr (),
        \<longrightarrow> impossible because both other lists have that
    - has non-None stored at a suffix of a value
        \<longrightarrow> but then value would have come from one list and non-None suffix from the other
            however, this would also lead to a contradiction
    - has something other than Inr stored at a prefix of a value/Inr
*)

lemma str_ord_delete_notin :
  assumes H : "strict_order (map fst a)"
  shows "(k, v) \<notin> set (str_ord_delete k a)" using H
proof(induction a arbitrary: k v)
  case Nil
  then show ?case by auto
next
  case (Cons ah at)
  have Ord_at : "strict_order (map fst at)" using strict_order_tl Cons by auto
  obtain ahk ahv where Ah : "ah = (ahk, ahv)" by (cases ah; auto)
  show ?case
  proof(cases "k = ahk")
    case True
    have "(ahk, v) \<notin> set at" using strict_order_distinct[OF Cons.prems(1)] Ah
        Set.imageI[of "(ahk, v)" "set at" fst]
      by(auto)
    then show ?thesis using Cons.prems Cons.IH[OF Ord_at] Ah True
      by(auto)
  next
    case False
    show ?thesis
    proof(cases "ahk < k")
      assume True' : "ahk < k"
      then show ?thesis using Ah Cons.prems Cons.IH[OF Ord_at, of k v] by(auto)
    next
      assume False' : "\<not> (ahk < k)"
      hence False'2 : "k < ahk" using False less_linear[of k ahk] by auto
      have Notin : "(k, v) \<notin> set at"
      proof
        assume Ctr: "(k, v) \<in> set at"
        then obtain idx where Idx : "idx < length at" "at ! idx = (k, v)"
          by(auto simp add:List.in_set_conv_nth)
        thus False using strict_order_unfold[OF Cons.prems(1), of "1 + idx" 0] Ah False'2
          by auto
      qed
      then show ?thesis using Cons.prems Cons.IH[OF Ord_at, of k v] Ah False'2 by(auto)
    qed
  qed
qed

lemma str_ord_delete_in :
  assumes H : "strict_order (map fst a)"
  assumes Hkv : "(k, v) \<in> set a"
  assumes Hneq : "k \<noteq> k'"
  shows "(k, v) \<in> set (str_ord_delete k' a)" using H Hkv Hneq
proof(induction a arbitrary: k k' v)
  case Nil
  then show ?case by auto
next
  case (Cons ah at)
  obtain kh kt where Ah : "ah = (kh, kt)" by (cases ah; auto)
  hence H' : "strict_order (map fst at)" using strict_order_tl[of "kh" "map fst at"] Cons.prems
    by(auto)
  then show ?case
(* need 2 layers of cases *)
  proof(cases "kh = k")
    case True
    then show ?thesis
    proof(cases "kh = k'")
      assume True' : "kh = k'"
      then show ?thesis using True H' Cons by(auto)
    next
      assume False' : "kh \<noteq> k'"
      then show ?thesis using True H' Cons Ah
        by(auto)
    qed
  next
    case False
    then show ?thesis
    proof(cases "kh = k'")
      assume True' : "kh = k'"
      then show ?thesis using False H' Cons Ah by(auto)
    next
      assume False' : "kh \<noteq> k'"
      then show ?thesis using False H' Cons Ah
        by(auto)
    qed
  qed
qed
*)

(* elem lemma needed. *)

fun roalist_gathers' ::
  "('k :: linorder, 'v, 'd) roalist' \<Rightarrow> 'k list \<Rightarrow> ('k :: linorder, 'v, 'd) roalist'" where
"roalist_gathers' [] _ = []"
| "roalist_gathers' ((kh, vh)#l) k =
  ( if is_prefix k kh then ((drop (length k) kh, vh) # roalist_gathers' l k)
    else roalist_gathers' l k)"

(*
lemma roalist_gather'_elem :
  assumes Hord : "strict_order (map fst l)"
  assumes H : "(kt, v) \<in> set (roalist_gather' l kh)"
  shows "(kh#kt, v) \<in> set l" using Hord H
proof(induction l arbitrary: kh kt v)
  case Nil
  then show ?case by auto
next

lemma roalist_gathers'_order :
  assumes H1 : "strict_order (map fst l)"
  shows "strict_order (map fst (roalist_gathers' l k))" using H1
proof(induction l arbitrary: k)
  case Nil
  then show ?case
    by(auto)
next
  case (Cons h t)
  obtain kh vh where Hd : "(h = (kh, vh))" by(cases h; auto)
  have Hord' : "strict_order (map fst t)"
    using strict_order_tl Cons by auto

  then show ?case using Cons
  proof(cases "map fst (roalist_gathers' t k)")
    case Nil' : Nil
    then show ?thesis using Cons Hd
      by(auto simp add:strict_order_def)
  next
    case Cons' : (Cons h2 t2)
(*
    obtain kh2 vh2 where Hd2 : "(h2 = (kh2, vh2))"
      by(cases h2; auto)
*)
    then show ?thesis using Cons Hd Cons'
      apply(auto)
  qed
    apply(auto)
qed
*)

(* intuition: start by using completeness of "vanilla" oalists.
   however this upper bound may not be valid according to roalist rules,
   so we will need to find a possibly greater upper bound, and then
   show that anytihng between this and the "vanilla" sup
   is going to violate roalist rules.
*)
instantiation roalist :: (linorder, Pordc, Pordc) Pordc
begin
instance sorry
end
(*
instance proof
  fix a b :: "('a :: linorder, 'b :: Pordc) roalist"
  assume H : "has_ub {a, b}"

  show "has_sup {a, b}" using H unfolding has_ub_def has_sup_def is_sup_def is_least_def is_ub_def pleq_roalist
sorry
qed
*)
(*

instance proof
  fix a b :: "('a :: linorder, 'b :: Pordc) roalist"
  assume H : "has_ub {a, b}"

  show "has_sup {a, b}" using H unfolding has_ub_def has_sup_def is_sup_def is_least_def is_ub_def pleq_roalist
  proof(transfer)
    fix a b :: "('a :: linorder, 'b :: Pordc) roalist'"
    assume HA : "strict_order (map fst a) \<and> roalist_valid a"
    hence HA1 : "strict_order (map fst a)" and HA2 : "roalist_valid a" by auto
    hence HAD : "distinct (map fst a)" using strict_order_distinct by auto
    assume HB : "strict_order (map fst b) \<and> roalist_valid b"
    hence HB1 : "strict_order (map fst b)" and HB2: "roalist_valid b" by auto
    hence HBD : "distinct (map fst b)" using strict_order_distinct by auto
    assume H: "\<exists>aa\<in>{xs. strict_order (map fst xs) \<and> roalist_valid xs}.
            \<forall>x\<in>{a, b}. list_leq x aa"
    then obtain xs where
      Xs_ord : "strict_order (map fst xs)"
      and Xs_valid : "roalist_valid xs"
      and Xs_gt_a : "list_leq a xs"
      and Xs_gt_b :  "list_leq b xs"
      by auto

    obtain sup where Sup_ord : "strict_order (map fst sup)"
      and Sup_gt_a : "list_leq a sup"
      and Sup_gt_b :  "list_leq b sup"
      and Is_sup : "(\<And> ub'::('a, 'b) roalist'.
                     strict_order (map fst ub') \<Longrightarrow>
                     list_leq a ub' \<Longrightarrow> list_leq b ub' \<Longrightarrow> list_leq sup ub')"
      using list_complete[OF HA1 HB1 Xs_ord Xs_gt_a Xs_gt_b] by auto

    hence Is_sup' : "(\<And> ub'::('a, 'b) roalist'.
                     strict_order (map fst ub') \<Longrightarrow>
                     roalist_valid ub' \<Longrightarrow>
                     list_leq a ub' \<Longrightarrow> list_leq b ub' \<Longrightarrow> list_leq sup ub')" by auto

    have Sup_D : "distinct (map fst sup)" using strict_order_distinct Sup_ord by auto

    have Conc' : "roalist_valid sup"
    proof(rule roalist_valid_intro)
      show "map_of sup [] = Some (Inr ())"
      proof-
        have InrA : "map_of a [] = Some (Inr ())" using roalist_valid_elim1[OF HA2] by auto
        hence InrA' : "([], Inr ()) \<in> set a" using map_of_is_SomeI HAD by auto
        obtain b' where Conc' : "([], b') \<in> set sup" and B' : "Inr () <[ b'" using list_leqD[OF Sup_gt_a InrA']
          by auto
        have B'_is : "b' = Inr ()" using B' by(cases b'; auto simp add: unit_pleq sum_pleq)
        show "map_of sup [] = Some (Inr ())" using map_of_is_SomeI[OF Sup_D Conc'] B'_is
          by auto
      qed
    next
      fix pref v sufh suf
      assume Hmap: "map_of sup pref = Some (Inl v)"
      show "map_of sup (pref @ sufh # suf) = None"
      proof-
        consider
          (1) "map_of a pref = None" "map_of b pref = None" |
          (2) z1 where "map_of a pref = Some z1" "map_of b pref = None" |
          (3) z2 where "map_of a pref = None" "map_of b pref = Some z2" |
          (4) z1 z2 where "map_of a pref = Some z1" "map_of b pref = Some z2"
          by(cases "map_of a pref"; cases "map_of b pref"; auto)
        then show "map_of sup (pref @ sufh # suf) = None"
        proof cases
          case 1
          (* contradiction: sup can't be sup. *)
          (* need smart delete here - delete closure if its a closure, value if it's a value
              delete won't be guaranteed to be valid.
             (or, maybe just in this case, it will? *)
(* problem - we need to be able to deeply delete closures. our delete closure function
   only deletes closures at the top level. *)
          have BadSup : "list_leq sup (roalist_delete_clos' pref sup)"
          proof(rule Is_sup'[OF str_ord_delete_correct[OF Sup_ord]])
          proof(rule list_leqI[OF Sup_ord str_ord_delete_correct[OF Sup_ord]])
            fix k v
            assume Kv : "(k, v) \<in> set sup"
            show "\<exists>v'. (k, v') \<in> set (str_ord_delete pref sup) \<and> v <[ v'"
            proof(cases "k = pref")
              case True
              then show ?thesis using 1
            next
              case False
              then show ?thesis sorry
            qed
          (* lemma about delete needed *)
(*
          have False using list_leqD[OF BadSup map_of_SomeD[OF Hmap]] apply(auto)
          then show ?thesis
*)        show ?thesis sorry
        next
          case 2
          then show ?thesis sorry
        next
          case 3
          then show ?thesis sorry
        next
          case 4
          then show ?thesis sorry
        qed
      qed
    next
      fix pref x sufh suf
      assume Hmap : "map_of sup (pref @ sufh # suf) = Some x"
      show "map_of sup pref = Some (Inr ())"
        sorry
    qed

    thus "\<exists>aa\<in>{xs. strict_order (map fst xs) \<and> roalist_valid xs}.
              (\<forall>x\<in>{a, b}. list_leq x aa) \<and>
              (\<forall>a'\<in>{xs. strict_order (map fst xs) \<and> roalist_valid xs}.
                  (\<forall>x\<in>{a, b}. list_leq x a') \<longrightarrow> list_leq aa a')"
      using Sup_ord Sup_gt_a Sup_gt_b Is_sup
      by(auto)
  qed
qed
end
*)

instantiation roalist :: (linorder, Pordc, Pordc) Pordb
begin
definition bot_roalist :
  "\<bottom> = roa_empty"

instance sorry
end

lift_definition roalist_check_prefixes :: "('key :: linorder, 'value, 'd) roalist \<Rightarrow> 'key list \<Rightarrow> bool"
is roalist_check_prefixes' .

(* idea: this works like list bsup, except that
   we need to make sure we don't merge a value and a closure together. *)
fun roalist_bsup' :: "('key :: linorder, 'value :: Mergeable, 'd :: Mergeable) roalist' \<Rightarrow>
                      ('key, 'value, 'd) roalist' \<Rightarrow> ('key, 'value, 'd) roalist'" where
"roalist_bsup' l [] = l"
| "roalist_bsup' l ((rkh, Inl rv)#rt) =
   (case map_of l rkh of
      Some (Inl lv) \<Rightarrow> roalist_bsup' (str_ord_update rkh (Inl [^ lv, rv ^]) l) rt
      | Some (Inr _) \<Rightarrow> roalist_bsup' l rt
      | None \<Rightarrow>
        (if roalist_check_prefixes' l rkh
         then roalist_bsup' (str_ord_update rkh (Inl rv) l) rt
         else roalist_bsup' l rt))"
| "roalist_bsup' l ((rkh, Inr rv)#rt) =
    (case map_of l rkh of
      Some (Inl _) \<Rightarrow> roalist_bsup' l rt
      | Some (Inr lv) \<Rightarrow> roalist_bsup' (str_ord_update rkh (Inr [^ lv, rv ^]) l) rt
      | None \<Rightarrow> (if roalist_check_prefixes' l rkh
                 then roalist_bsup' (str_ord_update rkh (Inr rv) l) rt
                 else roalist_bsup' l rt))"

lift_definition roalist_bsup :: "('key :: linorder, 'value :: Mergeable, 'd :: Mergeable) roalist \<Rightarrow>
                                 ('key, 'value, 'd) roalist \<Rightarrow> ('key, 'value, 'd) roalist"
is roalist_bsup' sorry
(*
proof-
  show "\<And>list1 list2.
       strict_order (map fst list1) \<and>
       roalist_valid list1 \<Longrightarrow>
       strict_order (map fst list2) \<and>
       roalist_valid list2 \<Longrightarrow>
       strict_order (map fst (roalist_bsup' list1 list2)) \<and>
       roalist_valid (roalist_bsup' list1 list2)" sorry
qed
*)

instantiation roalist :: (linorder, Mergeable, Mergeable) Mergeable
begin

definition bsup_roalist :
"[^ x, y ^] = roalist_bsup x y"

instance sorry
end

instantiation roalist :: (linorder, Mergeable, Mergeable) Mergeableb
begin
instance proof qed
end

end