src/HOL/Library/RBT_Impl.thy
author Andreas Lochbihler
Wed Oct 10 13:03:50 2012 +0200 (2012-10-10)
changeset 49770 cf6a78acf445
parent 49480 4632b867fba7
child 49807 9a0843995fd3
permissions -rw-r--r--
efficient construction of red black trees from sorted associative lists
     1 (*  Title:      HOL/Library/RBT_Impl.thy
     2     Author:     Markus Reiter, TU Muenchen
     3     Author:     Alexander Krauss, TU Muenchen
     4 *)
     5 
     6 header {* Implementation of Red-Black Trees *}
     7 
     8 theory RBT_Impl
     9 imports Main
    10 begin
    11 
    12 text {*
    13   For applications, you should use theory @{text RBT} which defines
    14   an abstract type of red-black tree obeying the invariant.
    15 *}
    16 
    17 subsection {* Datatype of RB trees *}
    18 
    19 datatype color = R | B
    20 datatype ('a, 'b) rbt = Empty | Branch color "('a, 'b) rbt" 'a 'b "('a, 'b) rbt"
    21 
    22 lemma rbt_cases:
    23   obtains (Empty) "t = Empty" 
    24   | (Red) l k v r where "t = Branch R l k v r" 
    25   | (Black) l k v r where "t = Branch B l k v r"
    26 proof (cases t)
    27   case Empty with that show thesis by blast
    28 next
    29   case (Branch c) with that show thesis by (cases c) blast+
    30 qed
    31 
    32 subsection {* Tree properties *}
    33 
    34 subsubsection {* Content of a tree *}
    35 
    36 primrec entries :: "('a, 'b) rbt \<Rightarrow> ('a \<times> 'b) list"
    37 where 
    38   "entries Empty = []"
    39 | "entries (Branch _ l k v r) = entries l @ (k,v) # entries r"
    40 
    41 abbreviation (input) entry_in_tree :: "'a \<Rightarrow> 'b \<Rightarrow> ('a, 'b) rbt \<Rightarrow> bool"
    42 where
    43   "entry_in_tree k v t \<equiv> (k, v) \<in> set (entries t)"
    44 
    45 definition keys :: "('a, 'b) rbt \<Rightarrow> 'a list" where
    46   "keys t = map fst (entries t)"
    47 
    48 lemma keys_simps [simp, code]:
    49   "keys Empty = []"
    50   "keys (Branch c l k v r) = keys l @ k # keys r"
    51   by (simp_all add: keys_def)
    52 
    53 lemma entry_in_tree_keys:
    54   assumes "(k, v) \<in> set (entries t)"
    55   shows "k \<in> set (keys t)"
    56 proof -
    57   from assms have "fst (k, v) \<in> fst ` set (entries t)" by (rule imageI)
    58   then show ?thesis by (simp add: keys_def)
    59 qed
    60 
    61 lemma keys_entries:
    62   "k \<in> set (keys t) \<longleftrightarrow> (\<exists>v. (k, v) \<in> set (entries t))"
    63   by (auto intro: entry_in_tree_keys) (auto simp add: keys_def)
    64 
    65 lemma non_empty_rbt_keys: 
    66   "t \<noteq> rbt.Empty \<Longrightarrow> keys t \<noteq> []"
    67   by (cases t) simp_all
    68 
    69 subsubsection {* Search tree properties *}
    70 
    71 context ord begin
    72 
    73 definition rbt_less :: "'a \<Rightarrow> ('a, 'b) rbt \<Rightarrow> bool"
    74 where
    75   rbt_less_prop: "rbt_less k t \<longleftrightarrow> (\<forall>x\<in>set (keys t). x < k)"
    76 
    77 abbreviation rbt_less_symbol (infix "|\<guillemotleft>" 50)
    78 where "t |\<guillemotleft> x \<equiv> rbt_less x t"
    79 
    80 definition rbt_greater :: "'a \<Rightarrow> ('a, 'b) rbt \<Rightarrow> bool" (infix "\<guillemotleft>|" 50) 
    81 where
    82   rbt_greater_prop: "rbt_greater k t = (\<forall>x\<in>set (keys t). k < x)"
    83 
    84 lemma rbt_less_simps [simp]:
    85   "Empty |\<guillemotleft> k = True"
    86   "Branch c lt kt v rt |\<guillemotleft> k \<longleftrightarrow> kt < k \<and> lt |\<guillemotleft> k \<and> rt |\<guillemotleft> k"
    87   by (auto simp add: rbt_less_prop)
    88 
    89 lemma rbt_greater_simps [simp]:
    90   "k \<guillemotleft>| Empty = True"
    91   "k \<guillemotleft>| (Branch c lt kt v rt) \<longleftrightarrow> k < kt \<and> k \<guillemotleft>| lt \<and> k \<guillemotleft>| rt"
    92   by (auto simp add: rbt_greater_prop)
    93 
    94 lemmas rbt_ord_props = rbt_less_prop rbt_greater_prop
    95 
    96 lemmas rbt_greater_nit = rbt_greater_prop entry_in_tree_keys
    97 lemmas rbt_less_nit = rbt_less_prop entry_in_tree_keys
    98 
    99 lemma (in order)
   100   shows rbt_less_eq_trans: "l |\<guillemotleft> u \<Longrightarrow> u \<le> v \<Longrightarrow> l |\<guillemotleft> v"
   101   and rbt_less_trans: "t |\<guillemotleft> x \<Longrightarrow> x < y \<Longrightarrow> t |\<guillemotleft> y"
   102   and rbt_greater_eq_trans: "u \<le> v \<Longrightarrow> v \<guillemotleft>| r \<Longrightarrow> u \<guillemotleft>| r"
   103   and rbt_greater_trans: "x < y \<Longrightarrow> y \<guillemotleft>| t \<Longrightarrow> x \<guillemotleft>| t"
   104   by (auto simp: rbt_ord_props)
   105 
   106 primrec rbt_sorted :: "('a, 'b) rbt \<Rightarrow> bool"
   107 where
   108   "rbt_sorted Empty = True"
   109 | "rbt_sorted (Branch c l k v r) = (l |\<guillemotleft> k \<and> k \<guillemotleft>| r \<and> rbt_sorted l \<and> rbt_sorted r)"
   110 
   111 end
   112 
   113 context linorder begin
   114 
   115 lemma rbt_sorted_entries:
   116   "rbt_sorted t \<Longrightarrow> List.sorted (map fst (entries t))"
   117 by (induct t) 
   118   (force simp: sorted_append sorted_Cons rbt_ord_props 
   119       dest!: entry_in_tree_keys)+
   120 
   121 lemma distinct_entries:
   122   "rbt_sorted t \<Longrightarrow> distinct (map fst (entries t))"
   123 by (induct t) 
   124   (force simp: sorted_append sorted_Cons rbt_ord_props 
   125       dest!: entry_in_tree_keys)+
   126 
   127 lemma distinct_keys:
   128   "rbt_sorted t \<Longrightarrow> distinct (keys t)"
   129   by (simp add: distinct_entries keys_def)
   130 
   131 
   132 subsubsection {* Tree lookup *}
   133 
   134 primrec (in ord) rbt_lookup :: "('a, 'b) rbt \<Rightarrow> 'a \<rightharpoonup> 'b"
   135 where
   136   "rbt_lookup Empty k = None"
   137 | "rbt_lookup (Branch _ l x y r) k = 
   138    (if k < x then rbt_lookup l k else if x < k then rbt_lookup r k else Some y)"
   139 
   140 lemma rbt_lookup_keys: "rbt_sorted t \<Longrightarrow> dom (rbt_lookup t) = set (keys t)"
   141   by (induct t) (auto simp: dom_def rbt_greater_prop rbt_less_prop)
   142 
   143 lemma dom_rbt_lookup_Branch: 
   144   "rbt_sorted (Branch c t1 k v t2) \<Longrightarrow> 
   145     dom (rbt_lookup (Branch c t1 k v t2)) 
   146     = Set.insert k (dom (rbt_lookup t1) \<union> dom (rbt_lookup t2))"
   147 proof -
   148   assume "rbt_sorted (Branch c t1 k v t2)"
   149   moreover from this have "rbt_sorted t1" "rbt_sorted t2" by simp_all
   150   ultimately show ?thesis by (simp add: rbt_lookup_keys)
   151 qed
   152 
   153 lemma finite_dom_rbt_lookup [simp, intro!]: "finite (dom (rbt_lookup t))"
   154 proof (induct t)
   155   case Empty then show ?case by simp
   156 next
   157   case (Branch color t1 a b t2)
   158   let ?A = "Set.insert a (dom (rbt_lookup t1) \<union> dom (rbt_lookup t2))"
   159   have "dom (rbt_lookup (Branch color t1 a b t2)) \<subseteq> ?A" by (auto split: split_if_asm)
   160   moreover from Branch have "finite (insert a (dom (rbt_lookup t1) \<union> dom (rbt_lookup t2)))" by simp
   161   ultimately show ?case by (rule finite_subset)
   162 qed 
   163 
   164 end
   165 
   166 context ord begin
   167 
   168 lemma rbt_lookup_rbt_less[simp]: "t |\<guillemotleft> k \<Longrightarrow> rbt_lookup t k = None" 
   169 by (induct t) auto
   170 
   171 lemma rbt_lookup_rbt_greater[simp]: "k \<guillemotleft>| t \<Longrightarrow> rbt_lookup t k = None"
   172 by (induct t) auto
   173 
   174 lemma rbt_lookup_Empty: "rbt_lookup Empty = empty"
   175 by (rule ext) simp
   176 
   177 end
   178 
   179 context linorder begin
   180 
   181 lemma map_of_entries:
   182   "rbt_sorted t \<Longrightarrow> map_of (entries t) = rbt_lookup t"
   183 proof (induct t)
   184   case Empty thus ?case by (simp add: rbt_lookup_Empty)
   185 next
   186   case (Branch c t1 k v t2)
   187   have "rbt_lookup (Branch c t1 k v t2) = rbt_lookup t2 ++ [k\<mapsto>v] ++ rbt_lookup t1"
   188   proof (rule ext)
   189     fix x
   190     from Branch have RBT_SORTED: "rbt_sorted (Branch c t1 k v t2)" by simp
   191     let ?thesis = "rbt_lookup (Branch c t1 k v t2) x = (rbt_lookup t2 ++ [k \<mapsto> v] ++ rbt_lookup t1) x"
   192 
   193     have DOM_T1: "!!k'. k'\<in>dom (rbt_lookup t1) \<Longrightarrow> k>k'"
   194     proof -
   195       fix k'
   196       from RBT_SORTED have "t1 |\<guillemotleft> k" by simp
   197       with rbt_less_prop have "\<forall>k'\<in>set (keys t1). k>k'" by auto
   198       moreover assume "k'\<in>dom (rbt_lookup t1)"
   199       ultimately show "k>k'" using rbt_lookup_keys RBT_SORTED by auto
   200     qed
   201     
   202     have DOM_T2: "!!k'. k'\<in>dom (rbt_lookup t2) \<Longrightarrow> k<k'"
   203     proof -
   204       fix k'
   205       from RBT_SORTED have "k \<guillemotleft>| t2" by simp
   206       with rbt_greater_prop have "\<forall>k'\<in>set (keys t2). k<k'" by auto
   207       moreover assume "k'\<in>dom (rbt_lookup t2)"
   208       ultimately show "k<k'" using rbt_lookup_keys RBT_SORTED by auto
   209     qed
   210     
   211     {
   212       assume C: "x<k"
   213       hence "rbt_lookup (Branch c t1 k v t2) x = rbt_lookup t1 x" by simp
   214       moreover from C have "x\<notin>dom [k\<mapsto>v]" by simp
   215       moreover have "x \<notin> dom (rbt_lookup t2)"
   216       proof
   217         assume "x \<in> dom (rbt_lookup t2)"
   218         with DOM_T2 have "k<x" by blast
   219         with C show False by simp
   220       qed
   221       ultimately have ?thesis by (simp add: map_add_upd_left map_add_dom_app_simps)
   222     } moreover {
   223       assume [simp]: "x=k"
   224       hence "rbt_lookup (Branch c t1 k v t2) x = [k \<mapsto> v] x" by simp
   225       moreover have "x \<notin> dom (rbt_lookup t1)" 
   226       proof
   227         assume "x \<in> dom (rbt_lookup t1)"
   228         with DOM_T1 have "k>x" by blast
   229         thus False by simp
   230       qed
   231       ultimately have ?thesis by (simp add: map_add_upd_left map_add_dom_app_simps)
   232     } moreover {
   233       assume C: "x>k"
   234       hence "rbt_lookup (Branch c t1 k v t2) x = rbt_lookup t2 x" by (simp add: less_not_sym[of k x])
   235       moreover from C have "x\<notin>dom [k\<mapsto>v]" by simp
   236       moreover have "x\<notin>dom (rbt_lookup t1)" proof
   237         assume "x\<in>dom (rbt_lookup t1)"
   238         with DOM_T1 have "k>x" by simp
   239         with C show False by simp
   240       qed
   241       ultimately have ?thesis by (simp add: map_add_upd_left map_add_dom_app_simps)
   242     } ultimately show ?thesis using less_linear by blast
   243   qed
   244   also from Branch 
   245   have "rbt_lookup t2 ++ [k \<mapsto> v] ++ rbt_lookup t1 = map_of (entries (Branch c t1 k v t2))" by simp
   246   finally show ?case by simp
   247 qed
   248 
   249 lemma rbt_lookup_in_tree: "rbt_sorted t \<Longrightarrow> rbt_lookup t k = Some v \<longleftrightarrow> (k, v) \<in> set (entries t)"
   250   by (simp add: map_of_entries [symmetric] distinct_entries)
   251 
   252 lemma set_entries_inject:
   253   assumes rbt_sorted: "rbt_sorted t1" "rbt_sorted t2" 
   254   shows "set (entries t1) = set (entries t2) \<longleftrightarrow> entries t1 = entries t2"
   255 proof -
   256   from rbt_sorted have "distinct (map fst (entries t1))"
   257     "distinct (map fst (entries t2))"
   258     by (auto intro: distinct_entries)
   259   with rbt_sorted show ?thesis
   260     by (auto intro: map_sorted_distinct_set_unique rbt_sorted_entries simp add: distinct_map)
   261 qed
   262 
   263 lemma entries_eqI:
   264   assumes rbt_sorted: "rbt_sorted t1" "rbt_sorted t2" 
   265   assumes rbt_lookup: "rbt_lookup t1 = rbt_lookup t2"
   266   shows "entries t1 = entries t2"
   267 proof -
   268   from rbt_sorted rbt_lookup have "map_of (entries t1) = map_of (entries t2)"
   269     by (simp add: map_of_entries)
   270   with rbt_sorted have "set (entries t1) = set (entries t2)"
   271     by (simp add: map_of_inject_set distinct_entries)
   272   with rbt_sorted show ?thesis by (simp add: set_entries_inject)
   273 qed
   274 
   275 lemma entries_rbt_lookup:
   276   assumes "rbt_sorted t1" "rbt_sorted t2" 
   277   shows "entries t1 = entries t2 \<longleftrightarrow> rbt_lookup t1 = rbt_lookup t2"
   278   using assms by (auto intro: entries_eqI simp add: map_of_entries [symmetric])
   279 
   280 lemma rbt_lookup_from_in_tree: 
   281   assumes "rbt_sorted t1" "rbt_sorted t2" 
   282   and "\<And>v. (k, v) \<in> set (entries t1) \<longleftrightarrow> (k, v) \<in> set (entries t2)" 
   283   shows "rbt_lookup t1 k = rbt_lookup t2 k"
   284 proof -
   285   from assms have "k \<in> dom (rbt_lookup t1) \<longleftrightarrow> k \<in> dom (rbt_lookup t2)"
   286     by (simp add: keys_entries rbt_lookup_keys)
   287   with assms show ?thesis by (auto simp add: rbt_lookup_in_tree [symmetric])
   288 qed
   289 
   290 end
   291 
   292 subsubsection {* Red-black properties *}
   293 
   294 primrec color_of :: "('a, 'b) rbt \<Rightarrow> color"
   295 where
   296   "color_of Empty = B"
   297 | "color_of (Branch c _ _ _ _) = c"
   298 
   299 primrec bheight :: "('a,'b) rbt \<Rightarrow> nat"
   300 where
   301   "bheight Empty = 0"
   302 | "bheight (Branch c lt k v rt) = (if c = B then Suc (bheight lt) else bheight lt)"
   303 
   304 primrec inv1 :: "('a, 'b) rbt \<Rightarrow> bool"
   305 where
   306   "inv1 Empty = True"
   307 | "inv1 (Branch c lt k v rt) \<longleftrightarrow> inv1 lt \<and> inv1 rt \<and> (c = B \<or> color_of lt = B \<and> color_of rt = B)"
   308 
   309 primrec inv1l :: "('a, 'b) rbt \<Rightarrow> bool" -- {* Weaker version *}
   310 where
   311   "inv1l Empty = True"
   312 | "inv1l (Branch c l k v r) = (inv1 l \<and> inv1 r)"
   313 lemma [simp]: "inv1 t \<Longrightarrow> inv1l t" by (cases t) simp+
   314 
   315 primrec inv2 :: "('a, 'b) rbt \<Rightarrow> bool"
   316 where
   317   "inv2 Empty = True"
   318 | "inv2 (Branch c lt k v rt) = (inv2 lt \<and> inv2 rt \<and> bheight lt = bheight rt)"
   319 
   320 context ord begin
   321 
   322 definition is_rbt :: "('a, 'b) rbt \<Rightarrow> bool" where
   323   "is_rbt t \<longleftrightarrow> inv1 t \<and> inv2 t \<and> color_of t = B \<and> rbt_sorted t"
   324 
   325 lemma is_rbt_rbt_sorted [simp]:
   326   "is_rbt t \<Longrightarrow> rbt_sorted t" by (simp add: is_rbt_def)
   327 
   328 theorem Empty_is_rbt [simp]:
   329   "is_rbt Empty" by (simp add: is_rbt_def)
   330 
   331 end
   332 
   333 subsection {* Insertion *}
   334 
   335 fun (* slow, due to massive case splitting *)
   336   balance :: "('a,'b) rbt \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   337 where
   338   "balance (Branch R a w x b) s t (Branch R c y z d) = Branch R (Branch B a w x b) s t (Branch B c y z d)" |
   339   "balance (Branch R (Branch R a w x b) s t c) y z d = Branch R (Branch B a w x b) s t (Branch B c y z d)" |
   340   "balance (Branch R a w x (Branch R b s t c)) y z d = Branch R (Branch B a w x b) s t (Branch B c y z d)" |
   341   "balance a w x (Branch R b s t (Branch R c y z d)) = Branch R (Branch B a w x b) s t (Branch B c y z d)" |
   342   "balance a w x (Branch R (Branch R b s t c) y z d) = Branch R (Branch B a w x b) s t (Branch B c y z d)" |
   343   "balance a s t b = Branch B a s t b"
   344 
   345 lemma balance_inv1: "\<lbrakk>inv1l l; inv1l r\<rbrakk> \<Longrightarrow> inv1 (balance l k v r)" 
   346   by (induct l k v r rule: balance.induct) auto
   347 
   348 lemma balance_bheight: "bheight l = bheight r \<Longrightarrow> bheight (balance l k v r) = Suc (bheight l)"
   349   by (induct l k v r rule: balance.induct) auto
   350 
   351 lemma balance_inv2: 
   352   assumes "inv2 l" "inv2 r" "bheight l = bheight r"
   353   shows "inv2 (balance l k v r)"
   354   using assms
   355   by (induct l k v r rule: balance.induct) auto
   356 
   357 context ord begin
   358 
   359 lemma balance_rbt_greater[simp]: "(v \<guillemotleft>| balance a k x b) = (v \<guillemotleft>| a \<and> v \<guillemotleft>| b \<and> v < k)" 
   360   by (induct a k x b rule: balance.induct) auto
   361 
   362 lemma balance_rbt_less[simp]: "(balance a k x b |\<guillemotleft> v) = (a |\<guillemotleft> v \<and> b |\<guillemotleft> v \<and> k < v)"
   363   by (induct a k x b rule: balance.induct) auto
   364 
   365 end
   366 
   367 lemma (in linorder) balance_rbt_sorted: 
   368   fixes k :: "'a"
   369   assumes "rbt_sorted l" "rbt_sorted r" "l |\<guillemotleft> k" "k \<guillemotleft>| r"
   370   shows "rbt_sorted (balance l k v r)"
   371 using assms proof (induct l k v r rule: balance.induct)
   372   case ("2_2" a x w b y t c z s va vb vd vc)
   373   hence "y < z \<and> z \<guillemotleft>| Branch B va vb vd vc" 
   374     by (auto simp add: rbt_ord_props)
   375   hence "y \<guillemotleft>| (Branch B va vb vd vc)" by (blast dest: rbt_greater_trans)
   376   with "2_2" show ?case by simp
   377 next
   378   case ("3_2" va vb vd vc x w b y s c z)
   379   from "3_2" have "x < y \<and> Branch B va vb vd vc |\<guillemotleft> x" 
   380     by simp
   381   hence "Branch B va vb vd vc |\<guillemotleft> y" by (blast dest: rbt_less_trans)
   382   with "3_2" show ?case by simp
   383 next
   384   case ("3_3" x w b y s c z t va vb vd vc)
   385   from "3_3" have "y < z \<and> z \<guillemotleft>| Branch B va vb vd vc" by simp
   386   hence "y \<guillemotleft>| Branch B va vb vd vc" by (blast dest: rbt_greater_trans)
   387   with "3_3" show ?case by simp
   388 next
   389   case ("3_4" vd ve vg vf x w b y s c z t va vb vii vc)
   390   hence "x < y \<and> Branch B vd ve vg vf |\<guillemotleft> x" by simp
   391   hence 1: "Branch B vd ve vg vf |\<guillemotleft> y" by (blast dest: rbt_less_trans)
   392   from "3_4" have "y < z \<and> z \<guillemotleft>| Branch B va vb vii vc" by simp
   393   hence "y \<guillemotleft>| Branch B va vb vii vc" by (blast dest: rbt_greater_trans)
   394   with 1 "3_4" show ?case by simp
   395 next
   396   case ("4_2" va vb vd vc x w b y s c z t dd)
   397   hence "x < y \<and> Branch B va vb vd vc |\<guillemotleft> x" by simp
   398   hence "Branch B va vb vd vc |\<guillemotleft> y" by (blast dest: rbt_less_trans)
   399   with "4_2" show ?case by simp
   400 next
   401   case ("5_2" x w b y s c z t va vb vd vc)
   402   hence "y < z \<and> z \<guillemotleft>| Branch B va vb vd vc" by simp
   403   hence "y \<guillemotleft>| Branch B va vb vd vc" by (blast dest: rbt_greater_trans)
   404   with "5_2" show ?case by simp
   405 next
   406   case ("5_3" va vb vd vc x w b y s c z t)
   407   hence "x < y \<and> Branch B va vb vd vc |\<guillemotleft> x" by simp
   408   hence "Branch B va vb vd vc |\<guillemotleft> y" by (blast dest: rbt_less_trans)
   409   with "5_3" show ?case by simp
   410 next
   411   case ("5_4" va vb vg vc x w b y s c z t vd ve vii vf)
   412   hence "x < y \<and> Branch B va vb vg vc |\<guillemotleft> x" by simp
   413   hence 1: "Branch B va vb vg vc |\<guillemotleft> y" by (blast dest: rbt_less_trans)
   414   from "5_4" have "y < z \<and> z \<guillemotleft>| Branch B vd ve vii vf" by simp
   415   hence "y \<guillemotleft>| Branch B vd ve vii vf" by (blast dest: rbt_greater_trans)
   416   with 1 "5_4" show ?case by simp
   417 qed simp+
   418 
   419 lemma entries_balance [simp]:
   420   "entries (balance l k v r) = entries l @ (k, v) # entries r"
   421   by (induct l k v r rule: balance.induct) auto
   422 
   423 lemma keys_balance [simp]: 
   424   "keys (balance l k v r) = keys l @ k # keys r"
   425   by (simp add: keys_def)
   426 
   427 lemma balance_in_tree:  
   428   "entry_in_tree k x (balance l v y r) \<longleftrightarrow> entry_in_tree k x l \<or> k = v \<and> x = y \<or> entry_in_tree k x r"
   429   by (auto simp add: keys_def)
   430 
   431 lemma (in linorder) rbt_lookup_balance[simp]: 
   432 fixes k :: "'a"
   433 assumes "rbt_sorted l" "rbt_sorted r" "l |\<guillemotleft> k" "k \<guillemotleft>| r"
   434 shows "rbt_lookup (balance l k v r) x = rbt_lookup (Branch B l k v r) x"
   435 by (rule rbt_lookup_from_in_tree) (auto simp:assms balance_in_tree balance_rbt_sorted)
   436 
   437 primrec paint :: "color \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   438 where
   439   "paint c Empty = Empty"
   440 | "paint c (Branch _ l k v r) = Branch c l k v r"
   441 
   442 lemma paint_inv1l[simp]: "inv1l t \<Longrightarrow> inv1l (paint c t)" by (cases t) auto
   443 lemma paint_inv1[simp]: "inv1l t \<Longrightarrow> inv1 (paint B t)" by (cases t) auto
   444 lemma paint_inv2[simp]: "inv2 t \<Longrightarrow> inv2 (paint c t)" by (cases t) auto
   445 lemma paint_color_of[simp]: "color_of (paint B t) = B" by (cases t) auto
   446 lemma paint_in_tree[simp]: "entry_in_tree k x (paint c t) = entry_in_tree k x t" by (cases t) auto
   447 
   448 context ord begin
   449 
   450 lemma paint_rbt_sorted[simp]: "rbt_sorted t \<Longrightarrow> rbt_sorted (paint c t)" by (cases t) auto
   451 lemma paint_rbt_lookup[simp]: "rbt_lookup (paint c t) = rbt_lookup t" by (rule ext) (cases t, auto)
   452 lemma paint_rbt_greater[simp]: "(v \<guillemotleft>| paint c t) = (v \<guillemotleft>| t)" by (cases t) auto
   453 lemma paint_rbt_less[simp]: "(paint c t |\<guillemotleft> v) = (t |\<guillemotleft> v)" by (cases t) auto
   454 
   455 fun
   456   rbt_ins :: "('a \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   457 where
   458   "rbt_ins f k v Empty = Branch R Empty k v Empty" |
   459   "rbt_ins f k v (Branch B l x y r) = (if k < x then balance (rbt_ins f k v l) x y r
   460                                        else if k > x then balance l x y (rbt_ins f k v r)
   461                                        else Branch B l x (f k y v) r)" |
   462   "rbt_ins f k v (Branch R l x y r) = (if k < x then Branch R (rbt_ins f k v l) x y r
   463                                        else if k > x then Branch R l x y (rbt_ins f k v r)
   464                                        else Branch R l x (f k y v) r)"
   465 
   466 lemma ins_inv1_inv2: 
   467   assumes "inv1 t" "inv2 t"
   468   shows "inv2 (rbt_ins f k x t)" "bheight (rbt_ins f k x t) = bheight t" 
   469   "color_of t = B \<Longrightarrow> inv1 (rbt_ins f k x t)" "inv1l (rbt_ins f k x t)"
   470   using assms
   471   by (induct f k x t rule: rbt_ins.induct) (auto simp: balance_inv1 balance_inv2 balance_bheight)
   472 
   473 end
   474 
   475 context linorder begin
   476 
   477 lemma ins_rbt_greater[simp]: "(v \<guillemotleft>| rbt_ins f (k :: 'a) x t) = (v \<guillemotleft>| t \<and> k > v)"
   478   by (induct f k x t rule: rbt_ins.induct) auto
   479 lemma ins_rbt_less[simp]: "(rbt_ins f k x t |\<guillemotleft> v) = (t |\<guillemotleft> v \<and> k < v)"
   480   by (induct f k x t rule: rbt_ins.induct) auto
   481 lemma ins_rbt_sorted[simp]: "rbt_sorted t \<Longrightarrow> rbt_sorted (rbt_ins f k x t)"
   482   by (induct f k x t rule: rbt_ins.induct) (auto simp: balance_rbt_sorted)
   483 
   484 lemma keys_ins: "set (keys (rbt_ins f k v t)) = { k } \<union> set (keys t)"
   485   by (induct f k v t rule: rbt_ins.induct) auto
   486 
   487 lemma rbt_lookup_ins: 
   488   fixes k :: "'a"
   489   assumes "rbt_sorted t"
   490   shows "rbt_lookup (rbt_ins f k v t) x = ((rbt_lookup t)(k |-> case rbt_lookup t k of None \<Rightarrow> v 
   491                                                                 | Some w \<Rightarrow> f k w v)) x"
   492 using assms by (induct f k v t rule: rbt_ins.induct) auto
   493 
   494 end
   495 
   496 context ord begin
   497 
   498 definition rbt_insert_with_key :: "('a \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   499 where "rbt_insert_with_key f k v t = paint B (rbt_ins f k v t)"
   500 
   501 definition rbt_insertw_def: "rbt_insert_with f = rbt_insert_with_key (\<lambda>_. f)"
   502 
   503 definition rbt_insert :: "'a \<Rightarrow> 'b \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt" where
   504   "rbt_insert = rbt_insert_with_key (\<lambda>_ _ nv. nv)"
   505 
   506 end
   507 
   508 context linorder begin
   509 
   510 lemma rbt_insertwk_rbt_sorted: "rbt_sorted t \<Longrightarrow> rbt_sorted (rbt_insert_with_key f (k :: 'a) x t)"
   511   by (auto simp: rbt_insert_with_key_def)
   512 
   513 theorem rbt_insertwk_is_rbt: 
   514   assumes inv: "is_rbt t" 
   515   shows "is_rbt (rbt_insert_with_key f k x t)"
   516 using assms
   517 unfolding rbt_insert_with_key_def is_rbt_def
   518 by (auto simp: ins_inv1_inv2)
   519 
   520 lemma rbt_lookup_rbt_insertwk: 
   521   assumes "rbt_sorted t"
   522   shows "rbt_lookup (rbt_insert_with_key f k v t) x = ((rbt_lookup t)(k |-> case rbt_lookup t k of None \<Rightarrow> v 
   523                                                        | Some w \<Rightarrow> f k w v)) x"
   524 unfolding rbt_insert_with_key_def using assms
   525 by (simp add:rbt_lookup_ins)
   526 
   527 lemma rbt_insertw_rbt_sorted: "rbt_sorted t \<Longrightarrow> rbt_sorted (rbt_insert_with f k v t)" 
   528   by (simp add: rbt_insertwk_rbt_sorted rbt_insertw_def)
   529 theorem rbt_insertw_is_rbt: "is_rbt t \<Longrightarrow> is_rbt (rbt_insert_with f k v t)"
   530   by (simp add: rbt_insertwk_is_rbt rbt_insertw_def)
   531 
   532 lemma rbt_lookup_rbt_insertw:
   533   assumes "is_rbt t"
   534   shows "rbt_lookup (rbt_insert_with f k v t) = (rbt_lookup t)(k \<mapsto> (if k:dom (rbt_lookup t) then f (the (rbt_lookup t k)) v else v))"
   535 using assms
   536 unfolding rbt_insertw_def
   537 by (rule_tac ext) (cases "rbt_lookup t k", auto simp:rbt_lookup_rbt_insertwk dom_def)
   538 
   539 lemma rbt_insert_rbt_sorted: "rbt_sorted t \<Longrightarrow> rbt_sorted (rbt_insert k v t)"
   540   by (simp add: rbt_insertwk_rbt_sorted rbt_insert_def)
   541 theorem rbt_insert_is_rbt [simp]: "is_rbt t \<Longrightarrow> is_rbt (rbt_insert k v t)"
   542   by (simp add: rbt_insertwk_is_rbt rbt_insert_def)
   543 
   544 lemma rbt_lookup_rbt_insert: 
   545   assumes "is_rbt t"
   546   shows "rbt_lookup (rbt_insert k v t) = (rbt_lookup t)(k\<mapsto>v)"
   547 unfolding rbt_insert_def
   548 using assms
   549 by (rule_tac ext) (simp add: rbt_lookup_rbt_insertwk split:option.split)
   550 
   551 end
   552 
   553 subsection {* Deletion *}
   554 
   555 lemma bheight_paintR'[simp]: "color_of t = B \<Longrightarrow> bheight (paint R t) = bheight t - 1"
   556 by (cases t rule: rbt_cases) auto
   557 
   558 fun
   559   balance_left :: "('a,'b) rbt \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   560 where
   561   "balance_left (Branch R a k x b) s y c = Branch R (Branch B a k x b) s y c" |
   562   "balance_left bl k x (Branch B a s y b) = balance bl k x (Branch R a s y b)" |
   563   "balance_left bl k x (Branch R (Branch B a s y b) t z c) = Branch R (Branch B bl k x a) s y (balance b t z (paint R c))" |
   564   "balance_left t k x s = Empty"
   565 
   566 lemma balance_left_inv2_with_inv1:
   567   assumes "inv2 lt" "inv2 rt" "bheight lt + 1 = bheight rt" "inv1 rt"
   568   shows "bheight (balance_left lt k v rt) = bheight lt + 1"
   569   and   "inv2 (balance_left lt k v rt)"
   570 using assms 
   571 by (induct lt k v rt rule: balance_left.induct) (auto simp: balance_inv2 balance_bheight)
   572 
   573 lemma balance_left_inv2_app: 
   574   assumes "inv2 lt" "inv2 rt" "bheight lt + 1 = bheight rt" "color_of rt = B"
   575   shows "inv2 (balance_left lt k v rt)" 
   576         "bheight (balance_left lt k v rt) = bheight rt"
   577 using assms 
   578 by (induct lt k v rt rule: balance_left.induct) (auto simp add: balance_inv2 balance_bheight)+ 
   579 
   580 lemma balance_left_inv1: "\<lbrakk>inv1l a; inv1 b; color_of b = B\<rbrakk> \<Longrightarrow> inv1 (balance_left a k x b)"
   581   by (induct a k x b rule: balance_left.induct) (simp add: balance_inv1)+
   582 
   583 lemma balance_left_inv1l: "\<lbrakk> inv1l lt; inv1 rt \<rbrakk> \<Longrightarrow> inv1l (balance_left lt k x rt)"
   584 by (induct lt k x rt rule: balance_left.induct) (auto simp: balance_inv1)
   585 
   586 lemma (in linorder) balance_left_rbt_sorted: 
   587   "\<lbrakk> rbt_sorted l; rbt_sorted r; rbt_less k l; k \<guillemotleft>| r \<rbrakk> \<Longrightarrow> rbt_sorted (balance_left l k v r)"
   588 apply (induct l k v r rule: balance_left.induct)
   589 apply (auto simp: balance_rbt_sorted)
   590 apply (unfold rbt_greater_prop rbt_less_prop)
   591 by force+
   592 
   593 context order begin
   594 
   595 lemma balance_left_rbt_greater: 
   596   fixes k :: "'a"
   597   assumes "k \<guillemotleft>| a" "k \<guillemotleft>| b" "k < x" 
   598   shows "k \<guillemotleft>| balance_left a x t b"
   599 using assms 
   600 by (induct a x t b rule: balance_left.induct) auto
   601 
   602 lemma balance_left_rbt_less: 
   603   fixes k :: "'a"
   604   assumes "a |\<guillemotleft> k" "b |\<guillemotleft> k" "x < k" 
   605   shows "balance_left a x t b |\<guillemotleft> k"
   606 using assms
   607 by (induct a x t b rule: balance_left.induct) auto
   608 
   609 end
   610 
   611 lemma balance_left_in_tree: 
   612   assumes "inv1l l" "inv1 r" "bheight l + 1 = bheight r"
   613   shows "entry_in_tree k v (balance_left l a b r) = (entry_in_tree k v l \<or> k = a \<and> v = b \<or> entry_in_tree k v r)"
   614 using assms 
   615 by (induct l k v r rule: balance_left.induct) (auto simp: balance_in_tree)
   616 
   617 fun
   618   balance_right :: "('a,'b) rbt \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   619 where
   620   "balance_right a k x (Branch R b s y c) = Branch R a k x (Branch B b s y c)" |
   621   "balance_right (Branch B a k x b) s y bl = balance (Branch R a k x b) s y bl" |
   622   "balance_right (Branch R a k x (Branch B b s y c)) t z bl = Branch R (balance (paint R a) k x b) s y (Branch B c t z bl)" |
   623   "balance_right t k x s = Empty"
   624 
   625 lemma balance_right_inv2_with_inv1:
   626   assumes "inv2 lt" "inv2 rt" "bheight lt = bheight rt + 1" "inv1 lt"
   627   shows "inv2 (balance_right lt k v rt) \<and> bheight (balance_right lt k v rt) = bheight lt"
   628 using assms
   629 by (induct lt k v rt rule: balance_right.induct) (auto simp: balance_inv2 balance_bheight)
   630 
   631 lemma balance_right_inv1: "\<lbrakk>inv1 a; inv1l b; color_of a = B\<rbrakk> \<Longrightarrow> inv1 (balance_right a k x b)"
   632 by (induct a k x b rule: balance_right.induct) (simp add: balance_inv1)+
   633 
   634 lemma balance_right_inv1l: "\<lbrakk> inv1 lt; inv1l rt \<rbrakk> \<Longrightarrow>inv1l (balance_right lt k x rt)"
   635 by (induct lt k x rt rule: balance_right.induct) (auto simp: balance_inv1)
   636 
   637 lemma (in linorder) balance_right_rbt_sorted:
   638   "\<lbrakk> rbt_sorted l; rbt_sorted r; rbt_less k l; k \<guillemotleft>| r \<rbrakk> \<Longrightarrow> rbt_sorted (balance_right l k v r)"
   639 apply (induct l k v r rule: balance_right.induct)
   640 apply (auto simp:balance_rbt_sorted)
   641 apply (unfold rbt_less_prop rbt_greater_prop)
   642 by force+
   643 
   644 context order begin
   645 
   646 lemma balance_right_rbt_greater: 
   647   fixes k :: "'a"
   648   assumes "k \<guillemotleft>| a" "k \<guillemotleft>| b" "k < x" 
   649   shows "k \<guillemotleft>| balance_right a x t b"
   650 using assms by (induct a x t b rule: balance_right.induct) auto
   651 
   652 lemma balance_right_rbt_less: 
   653   fixes k :: "'a"
   654   assumes "a |\<guillemotleft> k" "b |\<guillemotleft> k" "x < k" 
   655   shows "balance_right a x t b |\<guillemotleft> k"
   656 using assms by (induct a x t b rule: balance_right.induct) auto
   657 
   658 end
   659 
   660 lemma balance_right_in_tree:
   661   assumes "inv1 l" "inv1l r" "bheight l = bheight r + 1" "inv2 l" "inv2 r"
   662   shows "entry_in_tree x y (balance_right l k v r) = (entry_in_tree x y l \<or> x = k \<and> y = v \<or> entry_in_tree x y r)"
   663 using assms by (induct l k v r rule: balance_right.induct) (auto simp: balance_in_tree)
   664 
   665 fun
   666   combine :: "('a,'b) rbt \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   667 where
   668   "combine Empty x = x" 
   669 | "combine x Empty = x" 
   670 | "combine (Branch R a k x b) (Branch R c s y d) = (case (combine b c) of
   671                                     Branch R b2 t z c2 \<Rightarrow> (Branch R (Branch R a k x b2) t z (Branch R c2 s y d)) |
   672                                     bc \<Rightarrow> Branch R a k x (Branch R bc s y d))" 
   673 | "combine (Branch B a k x b) (Branch B c s y d) = (case (combine b c) of
   674                                     Branch R b2 t z c2 \<Rightarrow> Branch R (Branch B a k x b2) t z (Branch B c2 s y d) |
   675                                     bc \<Rightarrow> balance_left a k x (Branch B bc s y d))" 
   676 | "combine a (Branch R b k x c) = Branch R (combine a b) k x c" 
   677 | "combine (Branch R a k x b) c = Branch R a k x (combine b c)" 
   678 
   679 lemma combine_inv2:
   680   assumes "inv2 lt" "inv2 rt" "bheight lt = bheight rt"
   681   shows "bheight (combine lt rt) = bheight lt" "inv2 (combine lt rt)"
   682 using assms 
   683 by (induct lt rt rule: combine.induct) 
   684    (auto simp: balance_left_inv2_app split: rbt.splits color.splits)
   685 
   686 lemma combine_inv1: 
   687   assumes "inv1 lt" "inv1 rt"
   688   shows "color_of lt = B \<Longrightarrow> color_of rt = B \<Longrightarrow> inv1 (combine lt rt)"
   689          "inv1l (combine lt rt)"
   690 using assms 
   691 by (induct lt rt rule: combine.induct)
   692    (auto simp: balance_left_inv1 split: rbt.splits color.splits)
   693 
   694 context linorder begin
   695 
   696 lemma combine_rbt_greater[simp]: 
   697   fixes k :: "'a"
   698   assumes "k \<guillemotleft>| l" "k \<guillemotleft>| r" 
   699   shows "k \<guillemotleft>| combine l r"
   700 using assms 
   701 by (induct l r rule: combine.induct)
   702    (auto simp: balance_left_rbt_greater split:rbt.splits color.splits)
   703 
   704 lemma combine_rbt_less[simp]: 
   705   fixes k :: "'a"
   706   assumes "l |\<guillemotleft> k" "r |\<guillemotleft> k" 
   707   shows "combine l r |\<guillemotleft> k"
   708 using assms 
   709 by (induct l r rule: combine.induct)
   710    (auto simp: balance_left_rbt_less split:rbt.splits color.splits)
   711 
   712 lemma combine_rbt_sorted: 
   713   fixes k :: "'a"
   714   assumes "rbt_sorted l" "rbt_sorted r" "l |\<guillemotleft> k" "k \<guillemotleft>| r"
   715   shows "rbt_sorted (combine l r)"
   716 using assms proof (induct l r rule: combine.induct)
   717   case (3 a x v b c y w d)
   718   hence ineqs: "a |\<guillemotleft> x" "x \<guillemotleft>| b" "b |\<guillemotleft> k" "k \<guillemotleft>| c" "c |\<guillemotleft> y" "y \<guillemotleft>| d"
   719     by auto
   720   with 3
   721   show ?case
   722     by (cases "combine b c" rule: rbt_cases)
   723       (auto, (metis combine_rbt_greater combine_rbt_less ineqs ineqs rbt_less_simps(2) rbt_greater_simps(2) rbt_greater_trans rbt_less_trans)+)
   724 next
   725   case (4 a x v b c y w d)
   726   hence "x < k \<and> rbt_greater k c" by simp
   727   hence "rbt_greater x c" by (blast dest: rbt_greater_trans)
   728   with 4 have 2: "rbt_greater x (combine b c)" by (simp add: combine_rbt_greater)
   729   from 4 have "k < y \<and> rbt_less k b" by simp
   730   hence "rbt_less y b" by (blast dest: rbt_less_trans)
   731   with 4 have 3: "rbt_less y (combine b c)" by (simp add: combine_rbt_less)
   732   show ?case
   733   proof (cases "combine b c" rule: rbt_cases)
   734     case Empty
   735     from 4 have "x < y \<and> rbt_greater y d" by auto
   736     hence "rbt_greater x d" by (blast dest: rbt_greater_trans)
   737     with 4 Empty have "rbt_sorted a" and "rbt_sorted (Branch B Empty y w d)"
   738       and "rbt_less x a" and "rbt_greater x (Branch B Empty y w d)" by auto
   739     with Empty show ?thesis by (simp add: balance_left_rbt_sorted)
   740   next
   741     case (Red lta va ka rta)
   742     with 2 4 have "x < va \<and> rbt_less x a" by simp
   743     hence 5: "rbt_less va a" by (blast dest: rbt_less_trans)
   744     from Red 3 4 have "va < y \<and> rbt_greater y d" by simp
   745     hence "rbt_greater va d" by (blast dest: rbt_greater_trans)
   746     with Red 2 3 4 5 show ?thesis by simp
   747   next
   748     case (Black lta va ka rta)
   749     from 4 have "x < y \<and> rbt_greater y d" by auto
   750     hence "rbt_greater x d" by (blast dest: rbt_greater_trans)
   751     with Black 2 3 4 have "rbt_sorted a" and "rbt_sorted (Branch B (combine b c) y w d)" 
   752       and "rbt_less x a" and "rbt_greater x (Branch B (combine b c) y w d)" by auto
   753     with Black show ?thesis by (simp add: balance_left_rbt_sorted)
   754   qed
   755 next
   756   case (5 va vb vd vc b x w c)
   757   hence "k < x \<and> rbt_less k (Branch B va vb vd vc)" by simp
   758   hence "rbt_less x (Branch B va vb vd vc)" by (blast dest: rbt_less_trans)
   759   with 5 show ?case by (simp add: combine_rbt_less)
   760 next
   761   case (6 a x v b va vb vd vc)
   762   hence "x < k \<and> rbt_greater k (Branch B va vb vd vc)" by simp
   763   hence "rbt_greater x (Branch B va vb vd vc)" by (blast dest: rbt_greater_trans)
   764   with 6 show ?case by (simp add: combine_rbt_greater)
   765 qed simp+
   766 
   767 end
   768 
   769 lemma combine_in_tree: 
   770   assumes "inv2 l" "inv2 r" "bheight l = bheight r" "inv1 l" "inv1 r"
   771   shows "entry_in_tree k v (combine l r) = (entry_in_tree k v l \<or> entry_in_tree k v r)"
   772 using assms 
   773 proof (induct l r rule: combine.induct)
   774   case (4 _ _ _ b c)
   775   hence a: "bheight (combine b c) = bheight b" by (simp add: combine_inv2)
   776   from 4 have b: "inv1l (combine b c)" by (simp add: combine_inv1)
   777 
   778   show ?case
   779   proof (cases "combine b c" rule: rbt_cases)
   780     case Empty
   781     with 4 a show ?thesis by (auto simp: balance_left_in_tree)
   782   next
   783     case (Red lta ka va rta)
   784     with 4 show ?thesis by auto
   785   next
   786     case (Black lta ka va rta)
   787     with a b 4  show ?thesis by (auto simp: balance_left_in_tree)
   788   qed 
   789 qed (auto split: rbt.splits color.splits)
   790 
   791 context ord begin
   792 
   793 fun
   794   rbt_del_from_left :: "'a \<Rightarrow> ('a,'b) rbt \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt" and
   795   rbt_del_from_right :: "'a \<Rightarrow> ('a,'b) rbt \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt" and
   796   rbt_del :: "'a\<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"
   797 where
   798   "rbt_del x Empty = Empty" |
   799   "rbt_del x (Branch c a y s b) = 
   800    (if x < y then rbt_del_from_left x a y s b 
   801     else (if x > y then rbt_del_from_right x a y s b else combine a b))" |
   802   "rbt_del_from_left x (Branch B lt z v rt) y s b = balance_left (rbt_del x (Branch B lt z v rt)) y s b" |
   803   "rbt_del_from_left x a y s b = Branch R (rbt_del x a) y s b" |
   804   "rbt_del_from_right x a y s (Branch B lt z v rt) = balance_right a y s (rbt_del x (Branch B lt z v rt))" | 
   805   "rbt_del_from_right x a y s b = Branch R a y s (rbt_del x b)"
   806 
   807 end
   808 
   809 context linorder begin
   810 
   811 lemma 
   812   assumes "inv2 lt" "inv1 lt"
   813   shows
   814   "\<lbrakk>inv2 rt; bheight lt = bheight rt; inv1 rt\<rbrakk> \<Longrightarrow>
   815    inv2 (rbt_del_from_left x lt k v rt) \<and> 
   816    bheight (rbt_del_from_left x lt k v rt) = bheight lt \<and> 
   817    (color_of lt = B \<and> color_of rt = B \<and> inv1 (rbt_del_from_left x lt k v rt) \<or> 
   818     (color_of lt \<noteq> B \<or> color_of rt \<noteq> B) \<and> inv1l (rbt_del_from_left x lt k v rt))"
   819   and "\<lbrakk>inv2 rt; bheight lt = bheight rt; inv1 rt\<rbrakk> \<Longrightarrow>
   820   inv2 (rbt_del_from_right x lt k v rt) \<and> 
   821   bheight (rbt_del_from_right x lt k v rt) = bheight lt \<and> 
   822   (color_of lt = B \<and> color_of rt = B \<and> inv1 (rbt_del_from_right x lt k v rt) \<or> 
   823    (color_of lt \<noteq> B \<or> color_of rt \<noteq> B) \<and> inv1l (rbt_del_from_right x lt k v rt))"
   824   and rbt_del_inv1_inv2: "inv2 (rbt_del x lt) \<and> (color_of lt = R \<and> bheight (rbt_del x lt) = bheight lt \<and> inv1 (rbt_del x lt) 
   825   \<or> color_of lt = B \<and> bheight (rbt_del x lt) = bheight lt - 1 \<and> inv1l (rbt_del x lt))"
   826 using assms
   827 proof (induct x lt k v rt and x lt k v rt and x lt rule: rbt_del_from_left_rbt_del_from_right_rbt_del.induct)
   828 case (2 y c _ y')
   829   have "y = y' \<or> y < y' \<or> y > y'" by auto
   830   thus ?case proof (elim disjE)
   831     assume "y = y'"
   832     with 2 show ?thesis by (cases c) (simp add: combine_inv2 combine_inv1)+
   833   next
   834     assume "y < y'"
   835     with 2 show ?thesis by (cases c) auto
   836   next
   837     assume "y' < y"
   838     with 2 show ?thesis by (cases c) auto
   839   qed
   840 next
   841   case (3 y lt z v rta y' ss bb) 
   842   thus ?case by (cases "color_of (Branch B lt z v rta) = B \<and> color_of bb = B") (simp add: balance_left_inv2_with_inv1 balance_left_inv1 balance_left_inv1l)+
   843 next
   844   case (5 y a y' ss lt z v rta)
   845   thus ?case by (cases "color_of a = B \<and> color_of (Branch B lt z v rta) = B") (simp add: balance_right_inv2_with_inv1 balance_right_inv1 balance_right_inv1l)+
   846 next
   847   case ("6_1" y a y' ss) thus ?case by (cases "color_of a = B \<and> color_of Empty = B") simp+
   848 qed auto
   849 
   850 lemma 
   851   rbt_del_from_left_rbt_less: "\<lbrakk> lt |\<guillemotleft> v; rt |\<guillemotleft> v; k < v\<rbrakk> \<Longrightarrow> rbt_del_from_left x lt k y rt |\<guillemotleft> v"
   852   and rbt_del_from_right_rbt_less: "\<lbrakk>lt |\<guillemotleft> v; rt |\<guillemotleft> v; k < v\<rbrakk> \<Longrightarrow> rbt_del_from_right x lt k y rt |\<guillemotleft> v"
   853   and rbt_del_rbt_less: "lt |\<guillemotleft> v \<Longrightarrow> rbt_del x lt |\<guillemotleft> v"
   854 by (induct x lt k y rt and x lt k y rt and x lt rule: rbt_del_from_left_rbt_del_from_right_rbt_del.induct) 
   855    (auto simp: balance_left_rbt_less balance_right_rbt_less)
   856 
   857 lemma rbt_del_from_left_rbt_greater: "\<lbrakk>v \<guillemotleft>| lt; v \<guillemotleft>| rt; k > v\<rbrakk> \<Longrightarrow> v \<guillemotleft>| rbt_del_from_left x lt k y rt"
   858   and rbt_del_from_right_rbt_greater: "\<lbrakk>v \<guillemotleft>| lt; v \<guillemotleft>| rt; k > v\<rbrakk> \<Longrightarrow> v \<guillemotleft>| rbt_del_from_right x lt k y rt"
   859   and rbt_del_rbt_greater: "v \<guillemotleft>| lt \<Longrightarrow> v \<guillemotleft>| rbt_del x lt"
   860 by (induct x lt k y rt and x lt k y rt and x lt rule: rbt_del_from_left_rbt_del_from_right_rbt_del.induct)
   861    (auto simp: balance_left_rbt_greater balance_right_rbt_greater)
   862 
   863 lemma "\<lbrakk>rbt_sorted lt; rbt_sorted rt; lt |\<guillemotleft> k; k \<guillemotleft>| rt\<rbrakk> \<Longrightarrow> rbt_sorted (rbt_del_from_left x lt k y rt)"
   864   and "\<lbrakk>rbt_sorted lt; rbt_sorted rt; lt |\<guillemotleft> k; k \<guillemotleft>| rt\<rbrakk> \<Longrightarrow> rbt_sorted (rbt_del_from_right x lt k y rt)"
   865   and rbt_del_rbt_sorted: "rbt_sorted lt \<Longrightarrow> rbt_sorted (rbt_del x lt)"
   866 proof (induct x lt k y rt and x lt k y rt and x lt rule: rbt_del_from_left_rbt_del_from_right_rbt_del.induct)
   867   case (3 x lta zz v rta yy ss bb)
   868   from 3 have "Branch B lta zz v rta |\<guillemotleft> yy" by simp
   869   hence "rbt_del x (Branch B lta zz v rta) |\<guillemotleft> yy" by (rule rbt_del_rbt_less)
   870   with 3 show ?case by (simp add: balance_left_rbt_sorted)
   871 next
   872   case ("4_2" x vaa vbb vdd vc yy ss bb)
   873   hence "Branch R vaa vbb vdd vc |\<guillemotleft> yy" by simp
   874   hence "rbt_del x (Branch R vaa vbb vdd vc) |\<guillemotleft> yy" by (rule rbt_del_rbt_less)
   875   with "4_2" show ?case by simp
   876 next
   877   case (5 x aa yy ss lta zz v rta) 
   878   hence "yy \<guillemotleft>| Branch B lta zz v rta" by simp
   879   hence "yy \<guillemotleft>| rbt_del x (Branch B lta zz v rta)" by (rule rbt_del_rbt_greater)
   880   with 5 show ?case by (simp add: balance_right_rbt_sorted)
   881 next
   882   case ("6_2" x aa yy ss vaa vbb vdd vc)
   883   hence "yy \<guillemotleft>| Branch R vaa vbb vdd vc" by simp
   884   hence "yy \<guillemotleft>| rbt_del x (Branch R vaa vbb vdd vc)" by (rule rbt_del_rbt_greater)
   885   with "6_2" show ?case by simp
   886 qed (auto simp: combine_rbt_sorted)
   887 
   888 lemma "\<lbrakk>rbt_sorted lt; rbt_sorted rt; lt |\<guillemotleft> kt; kt \<guillemotleft>| rt; inv1 lt; inv1 rt; inv2 lt; inv2 rt; bheight lt = bheight rt; x < kt\<rbrakk> \<Longrightarrow> entry_in_tree k v (rbt_del_from_left x lt kt y rt) = (False \<or> (x \<noteq> k \<and> entry_in_tree k v (Branch c lt kt y rt)))"
   889   and "\<lbrakk>rbt_sorted lt; rbt_sorted rt; lt |\<guillemotleft> kt; kt \<guillemotleft>| rt; inv1 lt; inv1 rt; inv2 lt; inv2 rt; bheight lt = bheight rt; x > kt\<rbrakk> \<Longrightarrow> entry_in_tree k v (rbt_del_from_right x lt kt y rt) = (False \<or> (x \<noteq> k \<and> entry_in_tree k v (Branch c lt kt y rt)))"
   890   and rbt_del_in_tree: "\<lbrakk>rbt_sorted t; inv1 t; inv2 t\<rbrakk> \<Longrightarrow> entry_in_tree k v (rbt_del x t) = (False \<or> (x \<noteq> k \<and> entry_in_tree k v t))"
   891 proof (induct x lt kt y rt and x lt kt y rt and x t rule: rbt_del_from_left_rbt_del_from_right_rbt_del.induct)
   892   case (2 xx c aa yy ss bb)
   893   have "xx = yy \<or> xx < yy \<or> xx > yy" by auto
   894   from this 2 show ?case proof (elim disjE)
   895     assume "xx = yy"
   896     with 2 show ?thesis proof (cases "xx = k")
   897       case True
   898       from 2 `xx = yy` `xx = k` have "rbt_sorted (Branch c aa yy ss bb) \<and> k = yy" by simp
   899       hence "\<not> entry_in_tree k v aa" "\<not> entry_in_tree k v bb" by (auto simp: rbt_less_nit rbt_greater_prop)
   900       with `xx = yy` 2 `xx = k` show ?thesis by (simp add: combine_in_tree)
   901     qed (simp add: combine_in_tree)
   902   qed simp+
   903 next    
   904   case (3 xx lta zz vv rta yy ss bb)
   905   def mt[simp]: mt == "Branch B lta zz vv rta"
   906   from 3 have "inv2 mt \<and> inv1 mt" by simp
   907   hence "inv2 (rbt_del xx mt) \<and> (color_of mt = R \<and> bheight (rbt_del xx mt) = bheight mt \<and> inv1 (rbt_del xx mt) \<or> color_of mt = B \<and> bheight (rbt_del xx mt) = bheight mt - 1 \<and> inv1l (rbt_del xx mt))" by (blast dest: rbt_del_inv1_inv2)
   908   with 3 have 4: "entry_in_tree k v (rbt_del_from_left xx mt yy ss bb) = (False \<or> xx \<noteq> k \<and> entry_in_tree k v mt \<or> (k = yy \<and> v = ss) \<or> entry_in_tree k v bb)" by (simp add: balance_left_in_tree)
   909   thus ?case proof (cases "xx = k")
   910     case True
   911     from 3 True have "yy \<guillemotleft>| bb \<and> yy > k" by simp
   912     hence "k \<guillemotleft>| bb" by (blast dest: rbt_greater_trans)
   913     with 3 4 True show ?thesis by (auto simp: rbt_greater_nit)
   914   qed auto
   915 next
   916   case ("4_1" xx yy ss bb)
   917   show ?case proof (cases "xx = k")
   918     case True
   919     with "4_1" have "yy \<guillemotleft>| bb \<and> k < yy" by simp
   920     hence "k \<guillemotleft>| bb" by (blast dest: rbt_greater_trans)
   921     with "4_1" `xx = k` 
   922    have "entry_in_tree k v (Branch R Empty yy ss bb) = entry_in_tree k v Empty" by (auto simp: rbt_greater_nit)
   923     thus ?thesis by auto
   924   qed simp+
   925 next
   926   case ("4_2" xx vaa vbb vdd vc yy ss bb)
   927   thus ?case proof (cases "xx = k")
   928     case True
   929     with "4_2" have "k < yy \<and> yy \<guillemotleft>| bb" by simp
   930     hence "k \<guillemotleft>| bb" by (blast dest: rbt_greater_trans)
   931     with True "4_2" show ?thesis by (auto simp: rbt_greater_nit)
   932   qed auto
   933 next
   934   case (5 xx aa yy ss lta zz vv rta)
   935   def mt[simp]: mt == "Branch B lta zz vv rta"
   936   from 5 have "inv2 mt \<and> inv1 mt" by simp
   937   hence "inv2 (rbt_del xx mt) \<and> (color_of mt = R \<and> bheight (rbt_del xx mt) = bheight mt \<and> inv1 (rbt_del xx mt) \<or> color_of mt = B \<and> bheight (rbt_del xx mt) = bheight mt - 1 \<and> inv1l (rbt_del xx mt))" by (blast dest: rbt_del_inv1_inv2)
   938   with 5 have 3: "entry_in_tree k v (rbt_del_from_right xx aa yy ss mt) = (entry_in_tree k v aa \<or> (k = yy \<and> v = ss) \<or> False \<or> xx \<noteq> k \<and> entry_in_tree k v mt)" by (simp add: balance_right_in_tree)
   939   thus ?case proof (cases "xx = k")
   940     case True
   941     from 5 True have "aa |\<guillemotleft> yy \<and> yy < k" by simp
   942     hence "aa |\<guillemotleft> k" by (blast dest: rbt_less_trans)
   943     with 3 5 True show ?thesis by (auto simp: rbt_less_nit)
   944   qed auto
   945 next
   946   case ("6_1" xx aa yy ss)
   947   show ?case proof (cases "xx = k")
   948     case True
   949     with "6_1" have "aa |\<guillemotleft> yy \<and> k > yy" by simp
   950     hence "aa |\<guillemotleft> k" by (blast dest: rbt_less_trans)
   951     with "6_1" `xx = k` show ?thesis by (auto simp: rbt_less_nit)
   952   qed simp
   953 next
   954   case ("6_2" xx aa yy ss vaa vbb vdd vc)
   955   thus ?case proof (cases "xx = k")
   956     case True
   957     with "6_2" have "k > yy \<and> aa |\<guillemotleft> yy" by simp
   958     hence "aa |\<guillemotleft> k" by (blast dest: rbt_less_trans)
   959     with True "6_2" show ?thesis by (auto simp: rbt_less_nit)
   960   qed auto
   961 qed simp
   962 
   963 definition (in ord) rbt_delete where
   964   "rbt_delete k t = paint B (rbt_del k t)"
   965 
   966 theorem rbt_delete_is_rbt [simp]: assumes "is_rbt t" shows "is_rbt (rbt_delete k t)"
   967 proof -
   968   from assms have "inv2 t" and "inv1 t" unfolding is_rbt_def by auto 
   969   hence "inv2 (rbt_del k t) \<and> (color_of t = R \<and> bheight (rbt_del k t) = bheight t \<and> inv1 (rbt_del k t) \<or> color_of t = B \<and> bheight (rbt_del k t) = bheight t - 1 \<and> inv1l (rbt_del k t))" by (rule rbt_del_inv1_inv2)
   970   hence "inv2 (rbt_del k t) \<and> inv1l (rbt_del k t)" by (cases "color_of t") auto
   971   with assms show ?thesis
   972     unfolding is_rbt_def rbt_delete_def
   973     by (auto intro: paint_rbt_sorted rbt_del_rbt_sorted)
   974 qed
   975 
   976 lemma rbt_delete_in_tree: 
   977   assumes "is_rbt t" 
   978   shows "entry_in_tree k v (rbt_delete x t) = (x \<noteq> k \<and> entry_in_tree k v t)"
   979   using assms unfolding is_rbt_def rbt_delete_def
   980   by (auto simp: rbt_del_in_tree)
   981 
   982 lemma rbt_lookup_rbt_delete:
   983   assumes is_rbt: "is_rbt t"
   984   shows "rbt_lookup (rbt_delete k t) = (rbt_lookup t)|`(-{k})"
   985 proof
   986   fix x
   987   show "rbt_lookup (rbt_delete k t) x = (rbt_lookup t |` (-{k})) x" 
   988   proof (cases "x = k")
   989     assume "x = k" 
   990     with is_rbt show ?thesis
   991       by (cases "rbt_lookup (rbt_delete k t) k") (auto simp: rbt_lookup_in_tree rbt_delete_in_tree)
   992   next
   993     assume "x \<noteq> k"
   994     thus ?thesis
   995       by auto (metis is_rbt rbt_delete_is_rbt rbt_delete_in_tree is_rbt_rbt_sorted rbt_lookup_from_in_tree)
   996   qed
   997 qed
   998 
   999 end
  1000 
  1001 subsection {* Modifying existing entries *}
  1002 
  1003 context ord begin
  1004 
  1005 primrec
  1006   rbt_map_entry :: "'a \<Rightarrow> ('b \<Rightarrow> 'b) \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt"
  1007 where
  1008   "rbt_map_entry k f Empty = Empty"
  1009 | "rbt_map_entry k f (Branch c lt x v rt) =
  1010     (if k < x then Branch c (rbt_map_entry k f lt) x v rt
  1011     else if k > x then (Branch c lt x v (rbt_map_entry k f rt))
  1012     else Branch c lt x (f v) rt)"
  1013 
  1014 
  1015 lemma rbt_map_entry_color_of: "color_of (rbt_map_entry k f t) = color_of t" by (induct t) simp+
  1016 lemma rbt_map_entry_inv1: "inv1 (rbt_map_entry k f t) = inv1 t" by (induct t) (simp add: rbt_map_entry_color_of)+
  1017 lemma rbt_map_entry_inv2: "inv2 (rbt_map_entry k f t) = inv2 t" "bheight (rbt_map_entry k f t) = bheight t" by (induct t) simp+
  1018 lemma rbt_map_entry_rbt_greater: "rbt_greater a (rbt_map_entry k f t) = rbt_greater a t" by (induct t) simp+
  1019 lemma rbt_map_entry_rbt_less: "rbt_less a (rbt_map_entry k f t) = rbt_less a t" by (induct t) simp+
  1020 lemma rbt_map_entry_rbt_sorted: "rbt_sorted (rbt_map_entry k f t) = rbt_sorted t"
  1021   by (induct t) (simp_all add: rbt_map_entry_rbt_less rbt_map_entry_rbt_greater)
  1022 
  1023 theorem rbt_map_entry_is_rbt [simp]: "is_rbt (rbt_map_entry k f t) = is_rbt t" 
  1024 unfolding is_rbt_def by (simp add: rbt_map_entry_inv2 rbt_map_entry_color_of rbt_map_entry_rbt_sorted rbt_map_entry_inv1 )
  1025 
  1026 end
  1027 
  1028 theorem (in linorder) rbt_lookup_rbt_map_entry:
  1029   "rbt_lookup (rbt_map_entry k f t) = (rbt_lookup t)(k := Option.map f (rbt_lookup t k))"
  1030   by (induct t) (auto split: option.splits simp add: fun_eq_iff)
  1031 
  1032 subsection {* Mapping all entries *}
  1033 
  1034 primrec
  1035   map :: "('a \<Rightarrow> 'b \<Rightarrow> 'c) \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'c) rbt"
  1036 where
  1037   "map f Empty = Empty"
  1038 | "map f (Branch c lt k v rt) = Branch c (map f lt) k (f k v) (map f rt)"
  1039 
  1040 lemma map_entries [simp]: "entries (map f t) = List.map (\<lambda>(k, v). (k, f k v)) (entries t)"
  1041   by (induct t) auto
  1042 lemma map_keys [simp]: "keys (map f t) = keys t" by (simp add: keys_def split_def)
  1043 lemma map_color_of: "color_of (map f t) = color_of t" by (induct t) simp+
  1044 lemma map_inv1: "inv1 (map f t) = inv1 t" by (induct t) (simp add: map_color_of)+
  1045 lemma map_inv2: "inv2 (map f t) = inv2 t" "bheight (map f t) = bheight t" by (induct t) simp+
  1046 
  1047 context ord begin
  1048 
  1049 lemma map_rbt_greater: "rbt_greater k (map f t) = rbt_greater k t" by (induct t) simp+
  1050 lemma map_rbt_less: "rbt_less k (map f t) = rbt_less k t" by (induct t) simp+
  1051 lemma map_rbt_sorted: "rbt_sorted (map f t) = rbt_sorted t"  by (induct t) (simp add: map_rbt_less map_rbt_greater)+
  1052 theorem map_is_rbt [simp]: "is_rbt (map f t) = is_rbt t" 
  1053 unfolding is_rbt_def by (simp add: map_inv1 map_inv2 map_rbt_sorted map_color_of)
  1054 
  1055 end
  1056 
  1057 theorem (in linorder) rbt_lookup_map: "rbt_lookup (map f t) x = Option.map (f x) (rbt_lookup t x)"
  1058   apply(induct t)
  1059   apply auto
  1060   apply(subgoal_tac "x = a")
  1061   apply auto
  1062   done
  1063  (* FIXME: simproc "antisym less" does not work for linorder context, only for linorder type class
  1064     by (induct t) auto *)
  1065 
  1066 hide_const (open) map
  1067 
  1068 subsection {* Folding over entries *}
  1069 
  1070 definition fold :: "('a \<Rightarrow> 'b \<Rightarrow> 'c \<Rightarrow> 'c) \<Rightarrow> ('a, 'b) rbt \<Rightarrow> 'c \<Rightarrow> 'c" where
  1071   "fold f t = List.fold (prod_case f) (entries t)"
  1072 
  1073 lemma fold_simps [simp]:
  1074   "fold f Empty = id"
  1075   "fold f (Branch c lt k v rt) = fold f rt \<circ> f k v \<circ> fold f lt"
  1076   by (simp_all add: fold_def fun_eq_iff)
  1077 
  1078 lemma fold_code [code]:
  1079   "fold f Empty c = c"
  1080   "fold f (Branch c lt k v rt) c = fold f rt (f k v (fold f lt c))"
  1081 by(simp_all)
  1082 
  1083 (* fold with continuation predicate *)
  1084 
  1085 fun foldi :: "('c \<Rightarrow> bool) \<Rightarrow> ('a \<Rightarrow> 'b \<Rightarrow> 'c \<Rightarrow> 'c) \<Rightarrow> ('a :: linorder, 'b) rbt \<Rightarrow> 'c \<Rightarrow> 'c" 
  1086   where
  1087   "foldi c f Empty s = s" |
  1088   "foldi c f (Branch col l k v r) s = (
  1089     if (c s) then
  1090       let s' = foldi c f l s in
  1091         if (c s') then
  1092           foldi c f r (f k v s')
  1093         else s'
  1094     else 
  1095       s
  1096   )"
  1097 
  1098 subsection {* Bulkloading a tree *}
  1099 
  1100 definition (in ord) rbt_bulkload :: "('a \<times> 'b) list \<Rightarrow> ('a, 'b) rbt" where
  1101   "rbt_bulkload xs = foldr (\<lambda>(k, v). rbt_insert k v) xs Empty"
  1102 
  1103 context linorder begin
  1104 
  1105 lemma rbt_bulkload_is_rbt [simp, intro]:
  1106   "is_rbt (rbt_bulkload xs)"
  1107   unfolding rbt_bulkload_def by (induct xs) auto
  1108 
  1109 lemma rbt_lookup_rbt_bulkload:
  1110   "rbt_lookup (rbt_bulkload xs) = map_of xs"
  1111 proof -
  1112   obtain ys where "ys = rev xs" by simp
  1113   have "\<And>t. is_rbt t \<Longrightarrow>
  1114     rbt_lookup (List.fold (prod_case rbt_insert) ys t) = rbt_lookup t ++ map_of (rev ys)"
  1115       by (induct ys) (simp_all add: rbt_bulkload_def rbt_lookup_rbt_insert prod_case_beta)
  1116   from this Empty_is_rbt have
  1117     "rbt_lookup (List.fold (prod_case rbt_insert) (rev xs) Empty) = rbt_lookup Empty ++ map_of xs"
  1118      by (simp add: `ys = rev xs`)
  1119   then show ?thesis by (simp add: rbt_bulkload_def rbt_lookup_Empty foldr_conv_fold)
  1120 qed
  1121 
  1122 end
  1123 
  1124 
  1125 
  1126 subsection {* Building a RBT from a sorted list *}
  1127 
  1128 text {* 
  1129   These functions have been adapted from 
  1130   Andrew W. Appel, Efficient Verified Red-Black Trees (September 2011) 
  1131 *}
  1132 
  1133 fun rbtreeify_f :: "nat \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a, 'b) rbt \<times> ('a \<times> 'b) list"
  1134   and rbtreeify_g :: "nat \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a, 'b) rbt \<times> ('a \<times> 'b) list"
  1135 where
  1136   "rbtreeify_f n kvs =
  1137    (if n = 0 then (Empty, kvs)
  1138     else if n = 1 then
  1139       case kvs of (k, v) # kvs' \<Rightarrow> (Branch R Empty k v Empty, kvs')
  1140     else if (n mod 2 = 0) then
  1141       case rbtreeify_f (n div 2) kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1142         apfst (Branch B t1 k v) (rbtreeify_g (n div 2) kvs')
  1143     else case rbtreeify_f (n div 2) kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1144         apfst (Branch B t1 k v) (rbtreeify_f (n div 2) kvs'))"
  1145 
  1146 | "rbtreeify_g n kvs =
  1147    (if n = 0 \<or> n = 1 then (Empty, kvs)
  1148     else if n mod 2 = 0 then
  1149       case rbtreeify_g (n div 2) kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1150         apfst (Branch B t1 k v) (rbtreeify_g (n div 2) kvs')
  1151     else case rbtreeify_f (n div 2) kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1152         apfst (Branch B t1 k v) (rbtreeify_g (n div 2) kvs'))"
  1153 
  1154 definition rbtreeify :: "('a \<times> 'b) list \<Rightarrow> ('a, 'b) rbt"
  1155 where "rbtreeify kvs = fst (rbtreeify_g (Suc (length kvs)) kvs)"
  1156 
  1157 declare rbtreeify_f.simps [simp del] rbtreeify_g.simps [simp del]
  1158 
  1159 lemma rbtreeify_f_code [code]:
  1160   "rbtreeify_f n kvs =
  1161    (if n = 0 then (Empty, kvs)
  1162     else if n = 1 then
  1163       case kvs of (k, v) # kvs' \<Rightarrow> 
  1164         (Branch R Empty k v Empty, kvs')
  1165     else let (n', r) = divmod_nat n 2 in
  1166       if r = 0 then
  1167         case rbtreeify_f n' kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1168           apfst (Branch B t1 k v) (rbtreeify_g n' kvs')
  1169       else case rbtreeify_f n' kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1170           apfst (Branch B t1 k v) (rbtreeify_f n' kvs'))"
  1171 by(subst rbtreeify_f.simps)(simp only: Let_def divmod_nat_div_mod prod.simps)
  1172 
  1173 lemma rbtreeify_g_code [code]:
  1174   "rbtreeify_g n kvs =
  1175    (if n = 0 \<or> n = 1 then (Empty, kvs)
  1176     else let (n', r) = divmod_nat n 2 in
  1177       if r = 0 then
  1178         case rbtreeify_g n' kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1179           apfst (Branch B t1 k v) (rbtreeify_g n' kvs')
  1180       else case rbtreeify_f n' kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1181           apfst (Branch B t1 k v) (rbtreeify_g n' kvs'))"
  1182 by(subst rbtreeify_g.simps)(simp only: Let_def divmod_nat_div_mod prod.simps)
  1183 
  1184 lemma Suc_double_half: "Suc (2 * n) div 2 = n"
  1185 by simp
  1186 
  1187 lemma div2_plus_div2: "n div 2 + n div 2 = (n :: nat) - n mod 2"
  1188 by arith
  1189 
  1190 lemma rbtreeify_f_rec_aux_lemma:
  1191   "\<lbrakk>k - n div 2 = Suc k'; n \<le> k; n mod 2 = Suc 0\<rbrakk>
  1192   \<Longrightarrow> k' - n div 2 = k - n"
  1193 apply(rule add_right_imp_eq[where a = "n - n div 2"])
  1194 apply(subst add_diff_assoc2, arith)
  1195 apply(simp add: div2_plus_div2)
  1196 done
  1197 
  1198 lemma rbtreeify_f_simps:
  1199   "rbtreeify_f 0 kvs = (RBT_Impl.Empty, kvs)"
  1200   "rbtreeify_f (Suc 0) ((k, v) # kvs) = 
  1201   (Branch R Empty k v Empty, kvs)"
  1202   "0 < n \<Longrightarrow> rbtreeify_f (2 * n) kvs =
  1203    (case rbtreeify_f n kvs of (t1, (k, v) # kvs') \<Rightarrow>
  1204      apfst (Branch B t1 k v) (rbtreeify_g n kvs'))"
  1205   "0 < n \<Longrightarrow> rbtreeify_f (Suc (2 * n)) kvs =
  1206    (case rbtreeify_f n kvs of (t1, (k, v) # kvs') \<Rightarrow> 
  1207      apfst (Branch B t1 k v) (rbtreeify_f n kvs'))"
  1208 by(subst (1) rbtreeify_f.simps, simp add: Suc_double_half)+
  1209 
  1210 lemma rbtreeify_g_simps:
  1211   "rbtreeify_g 0 kvs = (Empty, kvs)"
  1212   "rbtreeify_g (Suc 0) kvs = (Empty, kvs)"
  1213   "0 < n \<Longrightarrow> rbtreeify_g (2 * n) kvs =
  1214    (case rbtreeify_g n kvs of (t1, (k, v) # kvs') \<Rightarrow> 
  1215      apfst (Branch B t1 k v) (rbtreeify_g n kvs'))"
  1216   "0 < n \<Longrightarrow> rbtreeify_g (Suc (2 * n)) kvs =
  1217    (case rbtreeify_f n kvs of (t1, (k, v) # kvs') \<Rightarrow> 
  1218      apfst (Branch B t1 k v) (rbtreeify_g n kvs'))"
  1219 by(subst (1) rbtreeify_g.simps, simp add: Suc_double_half)+
  1220 
  1221 declare rbtreeify_f_simps[simp] rbtreeify_g_simps[simp]
  1222 
  1223 lemma length_rbtreeify_f: "n \<le> length kvs
  1224   \<Longrightarrow> length (snd (rbtreeify_f n kvs)) = length kvs - n"
  1225   and length_rbtreeify_g:"\<lbrakk> 0 < n; n \<le> Suc (length kvs) \<rbrakk>
  1226   \<Longrightarrow> length (snd (rbtreeify_g n kvs)) = Suc (length kvs) - n"
  1227 proof(induction n kvs and n kvs rule: rbtreeify_f_rbtreeify_g.induct)
  1228   case (1 n kvs)
  1229   show ?case
  1230   proof(cases "n \<le> 1")
  1231     case True thus ?thesis using "1.prems"
  1232       by(cases n kvs rule: nat.exhaust[case_product list.exhaust]) auto
  1233   next
  1234     case False
  1235     hence "n \<noteq> 0" "n \<noteq> 1" by simp_all
  1236     note IH = "1.IH"[OF this]
  1237     show ?thesis
  1238     proof(cases "n mod 2 = 0")
  1239       case True
  1240       hence "length (snd (rbtreeify_f n kvs)) = 
  1241         length (snd (rbtreeify_f (2 * (n div 2)) kvs))"
  1242         by(metis minus_nat.diff_0 mult_div_cancel)
  1243       also from "1.prems" False obtain k v kvs' 
  1244         where kvs: "kvs = (k, v) # kvs'" by(cases kvs) auto
  1245       also have "0 < n div 2" using False by(simp) 
  1246       note rbtreeify_f_simps(3)[OF this]
  1247       also note kvs[symmetric] 
  1248       also let ?rest1 = "snd (rbtreeify_f (n div 2) kvs)"
  1249       from "1.prems" have "n div 2 \<le> length kvs" by simp
  1250       with True have len: "length ?rest1 = length kvs - n div 2" by(rule IH)
  1251       with "1.prems" False obtain t1 k' v' kvs''
  1252         where kvs'': "rbtreeify_f (n div 2) kvs = (t1, (k', v') # kvs'')"
  1253          by(cases ?rest1)(auto simp add: snd_def split: prod.split_asm)
  1254       note this also note prod.simps(2) also note list.simps(5) 
  1255       also note prod.simps(2) also note snd_apfst
  1256       also have "0 < n div 2" "n div 2 \<le> Suc (length kvs'')" 
  1257         using len "1.prems" False unfolding kvs'' by simp_all
  1258       with True kvs''[symmetric] refl refl
  1259       have "length (snd (rbtreeify_g (n div 2) kvs'')) = 
  1260         Suc (length kvs'') - n div 2" by(rule IH)
  1261       finally show ?thesis using len[unfolded kvs''] "1.prems" True
  1262         by(simp add: Suc_diff_le[symmetric] mult_2[symmetric] mult_div_cancel)
  1263     next
  1264       case False
  1265       hence "length (snd (rbtreeify_f n kvs)) = 
  1266         length (snd (rbtreeify_f (Suc (2 * (n div 2))) kvs))"
  1267         by(metis Suc_eq_plus1_left comm_semiring_1_class.normalizing_semiring_rules(7)
  1268              mod_2_not_eq_zero_eq_one_nat semiring_div_class.mod_div_equality')
  1269       also from "1.prems" `\<not> n \<le> 1` obtain k v kvs' 
  1270         where kvs: "kvs = (k, v) # kvs'" by(cases kvs) auto
  1271       also have "0 < n div 2" using `\<not> n \<le> 1` by(simp) 
  1272       note rbtreeify_f_simps(4)[OF this]
  1273       also note kvs[symmetric] 
  1274       also let ?rest1 = "snd (rbtreeify_f (n div 2) kvs)"
  1275       from "1.prems" have "n div 2 \<le> length kvs" by simp
  1276       with False have len: "length ?rest1 = length kvs - n div 2" by(rule IH)
  1277       with "1.prems" `\<not> n \<le> 1` obtain t1 k' v' kvs''
  1278         where kvs'': "rbtreeify_f (n div 2) kvs = (t1, (k', v') # kvs'')"
  1279         by(cases ?rest1)(auto simp add: snd_def split: prod.split_asm)
  1280       note this also note prod.simps(2) also note list.simps(5) 
  1281       also note prod.simps(2) also note snd_apfst
  1282       also have "n div 2 \<le> length kvs''" 
  1283         using len "1.prems" False unfolding kvs'' by simp arith
  1284       with False kvs''[symmetric] refl refl
  1285       have "length (snd (rbtreeify_f (n div 2) kvs'')) = length kvs'' - n div 2"
  1286         by(rule IH)
  1287       finally show ?thesis using len[unfolded kvs''] "1.prems" False
  1288         by simp(rule rbtreeify_f_rec_aux_lemma[OF sym])
  1289     qed
  1290   qed
  1291 next
  1292   case (2 n kvs)
  1293   show ?case
  1294   proof(cases "n > 1")
  1295     case False with `0 < n` show ?thesis
  1296       by(cases n kvs rule: nat.exhaust[case_product list.exhaust]) simp_all
  1297   next
  1298     case True
  1299     hence "\<not> (n = 0 \<or> n = 1)" by simp
  1300     note IH = "2.IH"[OF this]
  1301     show ?thesis
  1302     proof(cases "n mod 2 = 0")
  1303       case True
  1304       hence "length (snd (rbtreeify_g n kvs)) =
  1305         length (snd (rbtreeify_g (2 * (n div 2)) kvs))"
  1306         by(metis minus_nat.diff_0 mult_div_cancel)
  1307       also from "2.prems" True obtain k v kvs' 
  1308         where kvs: "kvs = (k, v) # kvs'" by(cases kvs) auto
  1309       also have "0 < n div 2" using `1 < n` by(simp) 
  1310       note rbtreeify_g_simps(3)[OF this]
  1311       also note kvs[symmetric] 
  1312       also let ?rest1 = "snd (rbtreeify_g (n div 2) kvs)"
  1313       from "2.prems" `1 < n`
  1314       have "0 < n div 2" "n div 2 \<le> Suc (length kvs)" by simp_all
  1315       with True have len: "length ?rest1 = Suc (length kvs) - n div 2" by(rule IH)
  1316       with "2.prems" obtain t1 k' v' kvs''
  1317         where kvs'': "rbtreeify_g (n div 2) kvs = (t1, (k', v') # kvs'')"
  1318         by(cases ?rest1)(auto simp add: snd_def split: prod.split_asm)
  1319       note this also note prod.simps(2) also note list.simps(5) 
  1320       also note prod.simps(2) also note snd_apfst
  1321       also have "n div 2 \<le> Suc (length kvs'')" 
  1322         using len "2.prems" unfolding kvs'' by simp
  1323       with True kvs''[symmetric] refl refl `0 < n div 2`
  1324       have "length (snd (rbtreeify_g (n div 2) kvs'')) = Suc (length kvs'') - n div 2"
  1325         by(rule IH)
  1326       finally show ?thesis using len[unfolded kvs''] "2.prems" True
  1327         by(simp add: Suc_diff_le[symmetric] mult_2[symmetric] mult_div_cancel)
  1328     next
  1329       case False
  1330       hence "length (snd (rbtreeify_g n kvs)) = 
  1331         length (snd (rbtreeify_g (Suc (2 * (n div 2))) kvs))"
  1332         by(metis Suc_eq_plus1_left comm_semiring_1_class.normalizing_semiring_rules(7) 
  1333             mod_2_not_eq_zero_eq_one_nat semiring_div_class.mod_div_equality')
  1334       also from "2.prems" `1 < n` obtain k v kvs'
  1335         where kvs: "kvs = (k, v) # kvs'" by(cases kvs) auto
  1336       also have "0 < n div 2" using `1 < n` by(simp)
  1337       note rbtreeify_g_simps(4)[OF this]
  1338       also note kvs[symmetric] 
  1339       also let ?rest1 = "snd (rbtreeify_f (n div 2) kvs)"
  1340       from "2.prems" have "n div 2 \<le> length kvs" by simp
  1341       with False have len: "length ?rest1 = length kvs - n div 2" by(rule IH)
  1342       with "2.prems" `1 < n` False obtain t1 k' v' kvs'' 
  1343         where kvs'': "rbtreeify_f (n div 2) kvs = (t1, (k', v') # kvs'')"
  1344         by(cases ?rest1)(auto simp add: snd_def split: prod.split_asm, arith)
  1345       note this also note prod.simps(2) also note list.simps(5) 
  1346       also note prod.simps(2) also note snd_apfst
  1347       also have "n div 2 \<le> Suc (length kvs'')" 
  1348         using len "2.prems" False unfolding kvs'' by simp arith
  1349       with False kvs''[symmetric] refl refl `0 < n div 2`
  1350       have "length (snd (rbtreeify_g (n div 2) kvs'')) = Suc (length kvs'') - n div 2"
  1351         by(rule IH)
  1352       finally show ?thesis using len[unfolded kvs''] "2.prems" False
  1353         by(simp add: div2_plus_div2)
  1354     qed
  1355   qed
  1356 qed
  1357 
  1358 lemma rbtreeify_induct [consumes 1, case_names f_0 f_1 f_even f_odd g_0 g_1 g_even g_odd]:
  1359   fixes P Q
  1360   defines "f0 == (\<And>kvs. P 0 kvs)"
  1361   and "f1 == (\<And>k v kvs. P (Suc 0) ((k, v) # kvs))"
  1362   and "feven ==
  1363     (\<And>n kvs t k v kvs'. \<lbrakk> n > 0; n \<le> length kvs; P n kvs; 
  1364        rbtreeify_f n kvs = (t, (k, v) # kvs'); n \<le> Suc (length kvs'); Q n kvs' \<rbrakk> 
  1365      \<Longrightarrow> P (2 * n) kvs)"
  1366   and "fodd == 
  1367     (\<And>n kvs t k v kvs'. \<lbrakk> n > 0; n \<le> length kvs; P n kvs;
  1368        rbtreeify_f n kvs = (t, (k, v) # kvs'); n \<le> length kvs'; P n kvs' \<rbrakk> 
  1369     \<Longrightarrow> P (Suc (2 * n)) kvs)"
  1370   and "g0 == (\<And>kvs. Q 0 kvs)"
  1371   and "g1 == (\<And>kvs. Q (Suc 0) kvs)"
  1372   and "geven == 
  1373     (\<And>n kvs t k v kvs'. \<lbrakk> n > 0; n \<le> Suc (length kvs); Q n kvs; 
  1374        rbtreeify_g n kvs = (t, (k, v) # kvs'); n \<le> Suc (length kvs'); Q n kvs' \<rbrakk>
  1375     \<Longrightarrow> Q (2 * n) kvs)"
  1376   and "godd == 
  1377     (\<And>n kvs t k v kvs'. \<lbrakk> n > 0; n \<le> length kvs; P n kvs;
  1378        rbtreeify_f n kvs = (t, (k, v) # kvs'); n \<le> Suc (length kvs'); Q n kvs' \<rbrakk>
  1379     \<Longrightarrow> Q (Suc (2 * n)) kvs)"
  1380   shows "\<lbrakk> n \<le> length kvs; 
  1381            PROP f0; PROP f1; PROP feven; PROP fodd; 
  1382            PROP g0; PROP g1; PROP geven; PROP godd \<rbrakk>
  1383          \<Longrightarrow> P n kvs"
  1384   and "\<lbrakk> n \<le> Suc (length kvs);
  1385           PROP f0; PROP f1; PROP feven; PROP fodd; 
  1386           PROP g0; PROP g1; PROP geven; PROP godd \<rbrakk>
  1387        \<Longrightarrow> Q n kvs"
  1388 proof -
  1389   assume f0: "PROP f0" and f1: "PROP f1" and feven: "PROP feven" and fodd: "PROP fodd"
  1390     and g0: "PROP g0" and g1: "PROP g1" and geven: "PROP geven" and godd: "PROP godd"
  1391   show "n \<le> length kvs \<Longrightarrow> P n kvs" and "n \<le> Suc (length kvs) \<Longrightarrow> Q n kvs"
  1392   proof(induction rule: rbtreeify_f_rbtreeify_g.induct)
  1393     case (1 n kvs)
  1394     show ?case
  1395     proof(cases "n \<le> 1")
  1396       case True thus ?thesis using "1.prems"
  1397         by(cases n kvs rule: nat.exhaust[case_product list.exhaust])
  1398           (auto simp add: f0[unfolded f0_def] f1[unfolded f1_def])
  1399     next
  1400       case False 
  1401       hence ns: "n \<noteq> 0" "n \<noteq> 1" by simp_all
  1402       hence ge0: "n div 2 > 0" by simp
  1403       note IH = "1.IH"[OF ns]
  1404       show ?thesis
  1405       proof(cases "n mod 2 = 0")
  1406         case True note ge0 
  1407         moreover from "1.prems" have n2: "n div 2 \<le> length kvs" by simp
  1408         moreover with True have "P (n div 2) kvs" by(rule IH)
  1409         moreover from length_rbtreeify_f[OF n2] ge0 "1.prems" obtain t k v kvs' 
  1410           where kvs': "rbtreeify_f (n div 2) kvs = (t, (k, v) # kvs')"
  1411           by(cases "snd (rbtreeify_f (n div 2) kvs)")
  1412             (auto simp add: snd_def split: prod.split_asm)
  1413         moreover from "1.prems" length_rbtreeify_f[OF n2] ge0
  1414         have "n div 2 \<le> Suc (length kvs')" by(simp add: kvs')
  1415         moreover with True kvs'[symmetric] refl refl
  1416         have "Q (n div 2) kvs'" by(rule IH)
  1417         moreover note feven[unfolded feven_def]
  1418           (* FIXME: why does by(rule feven[unfolded feven_def]) not work? *)
  1419         ultimately have "P (2 * (n div 2)) kvs" by -
  1420         thus ?thesis using True by (metis div_mod_equality' minus_nat.diff_0 nat_mult_commute)
  1421       next
  1422         case False note ge0
  1423         moreover from "1.prems" have n2: "n div 2 \<le> length kvs" by simp
  1424         moreover with False have "P (n div 2) kvs" by(rule IH)
  1425         moreover from length_rbtreeify_f[OF n2] ge0 "1.prems" obtain t k v kvs' 
  1426           where kvs': "rbtreeify_f (n div 2) kvs = (t, (k, v) # kvs')"
  1427           by(cases "snd (rbtreeify_f (n div 2) kvs)")
  1428             (auto simp add: snd_def split: prod.split_asm)
  1429         moreover from "1.prems" length_rbtreeify_f[OF n2] ge0 False
  1430         have "n div 2 \<le> length kvs'" by(simp add: kvs') arith
  1431         moreover with False kvs'[symmetric] refl refl have "P (n div 2) kvs'" by(rule IH)
  1432         moreover note fodd[unfolded fodd_def]
  1433         ultimately have "P (Suc (2 * (n div 2))) kvs" by -
  1434         thus ?thesis using False 
  1435           by simp (metis One_nat_def Suc_eq_plus1_left le_add_diff_inverse mod_less_eq_dividend mult_div_cancel)
  1436       qed
  1437     qed
  1438   next
  1439     case (2 n kvs)
  1440     show ?case
  1441     proof(cases "n \<le> 1")
  1442       case True thus ?thesis using "2.prems"
  1443         by(cases n kvs rule: nat.exhaust[case_product list.exhaust])
  1444           (auto simp add: g0[unfolded g0_def] g1[unfolded g1_def])
  1445     next
  1446       case False 
  1447       hence ns: "\<not> (n = 0 \<or> n = 1)" by simp
  1448       hence ge0: "n div 2 > 0" by simp
  1449       note IH = "2.IH"[OF ns]
  1450       show ?thesis
  1451       proof(cases "n mod 2 = 0")
  1452         case True note ge0
  1453         moreover from "2.prems" have n2: "n div 2 \<le> Suc (length kvs)" by simp
  1454         moreover with True have "Q (n div 2) kvs" by(rule IH)
  1455         moreover from length_rbtreeify_g[OF ge0 n2] ge0 "2.prems" obtain t k v kvs' 
  1456           where kvs': "rbtreeify_g (n div 2) kvs = (t, (k, v) # kvs')"
  1457           by(cases "snd (rbtreeify_g (n div 2) kvs)")
  1458             (auto simp add: snd_def split: prod.split_asm)
  1459         moreover from "2.prems" length_rbtreeify_g[OF ge0 n2] ge0
  1460         have "n div 2 \<le> Suc (length kvs')" by(simp add: kvs')
  1461         moreover with True kvs'[symmetric] refl refl 
  1462         have "Q (n div 2) kvs'" by(rule IH)
  1463         moreover note geven[unfolded geven_def]
  1464         ultimately have "Q (2 * (n div 2)) kvs" by -
  1465         thus ?thesis using True 
  1466           by(metis div_mod_equality' minus_nat.diff_0 nat_mult_commute)
  1467       next
  1468         case False note ge0
  1469         moreover from "2.prems" have n2: "n div 2 \<le> length kvs" by simp
  1470         moreover with False have "P (n div 2) kvs" by(rule IH)
  1471         moreover from length_rbtreeify_f[OF n2] ge0 "2.prems" False obtain t k v kvs' 
  1472           where kvs': "rbtreeify_f (n div 2) kvs = (t, (k, v) # kvs')"
  1473           by(cases "snd (rbtreeify_f (n div 2) kvs)")
  1474             (auto simp add: snd_def split: prod.split_asm, arith)
  1475         moreover from "2.prems" length_rbtreeify_f[OF n2] ge0 False
  1476         have "n div 2 \<le> Suc (length kvs')" by(simp add: kvs') arith
  1477         moreover with False kvs'[symmetric] refl refl
  1478         have "Q (n div 2) kvs'" by(rule IH)
  1479         moreover note godd[unfolded godd_def]
  1480         ultimately have "Q (Suc (2 * (n div 2))) kvs" by -
  1481         thus ?thesis using False 
  1482           by simp (metis One_nat_def Suc_eq_plus1_left le_add_diff_inverse mod_less_eq_dividend mult_div_cancel)
  1483       qed
  1484     qed
  1485   qed
  1486 qed
  1487 
  1488 lemma inv1_rbtreeify_f: "n \<le> length kvs 
  1489   \<Longrightarrow> inv1 (fst (rbtreeify_f n kvs))"
  1490   and inv1_rbtreeify_g: "n \<le> Suc (length kvs)
  1491   \<Longrightarrow> inv1 (fst (rbtreeify_g n kvs))"
  1492 by(induct n kvs and n kvs rule: rbtreeify_induct) simp_all
  1493 
  1494 fun plog2 :: "nat \<Rightarrow> nat" 
  1495 where "plog2 n = (if n \<le> 1 then 0 else plog2 (n div 2) + 1)"
  1496 
  1497 declare plog2.simps [simp del]
  1498 
  1499 lemma plog2_simps [simp]:
  1500   "plog2 0 = 0" "plog2 (Suc 0) = 0"
  1501   "0 < n \<Longrightarrow> plog2 (2 * n) = 1 + plog2 n"
  1502   "0 < n \<Longrightarrow> plog2 (Suc (2 * n)) = 1 + plog2 n"
  1503 by(subst plog2.simps, simp add: Suc_double_half)+
  1504 
  1505 lemma bheight_rbtreeify_f: "n \<le> length kvs
  1506   \<Longrightarrow> bheight (fst (rbtreeify_f n kvs)) = plog2 n"
  1507   and bheight_rbtreeify_g: "n \<le> Suc (length kvs)
  1508   \<Longrightarrow> bheight (fst (rbtreeify_g n kvs)) = plog2 n"
  1509 by(induct n kvs and n kvs rule: rbtreeify_induct) simp_all
  1510 
  1511 lemma bheight_rbtreeify_f_eq_plog2I:
  1512   "\<lbrakk> rbtreeify_f n kvs = (t, kvs'); n \<le> length kvs \<rbrakk> 
  1513   \<Longrightarrow> bheight t = plog2 n"
  1514 using bheight_rbtreeify_f[of n kvs] by simp
  1515 
  1516 lemma bheight_rbtreeify_g_eq_plog2I: 
  1517   "\<lbrakk> rbtreeify_g n kvs = (t, kvs'); n \<le> Suc (length kvs) \<rbrakk>
  1518   \<Longrightarrow> bheight t = plog2 n"
  1519 using bheight_rbtreeify_g[of n kvs] by simp
  1520 
  1521 hide_const (open) plog2
  1522 
  1523 lemma inv2_rbtreeify_f: "n \<le> length kvs
  1524   \<Longrightarrow> inv2 (fst (rbtreeify_f n kvs))"
  1525   and inv2_rbtreeify_g: "n \<le> Suc (length kvs)
  1526   \<Longrightarrow> inv2 (fst (rbtreeify_g n kvs))"
  1527 by(induct n kvs and n kvs rule: rbtreeify_induct)
  1528   (auto simp add: bheight_rbtreeify_f bheight_rbtreeify_g 
  1529         intro: bheight_rbtreeify_f_eq_plog2I bheight_rbtreeify_g_eq_plog2I)
  1530 
  1531 lemma "n \<le> length kvs \<Longrightarrow> True"
  1532   and color_of_rbtreeify_g:
  1533   "\<lbrakk> n \<le> Suc (length kvs); 0 < n \<rbrakk> 
  1534   \<Longrightarrow> color_of (fst (rbtreeify_g n kvs)) = B"
  1535 by(induct n kvs and n kvs rule: rbtreeify_induct) simp_all
  1536 
  1537 lemma entries_rbtreeify_f_append:
  1538   "n \<le> length kvs 
  1539   \<Longrightarrow> entries (fst (rbtreeify_f n kvs)) @ snd (rbtreeify_f n kvs) = kvs"
  1540   and entries_rbtreeify_g_append: 
  1541   "n \<le> Suc (length kvs) 
  1542   \<Longrightarrow> entries (fst (rbtreeify_g n kvs)) @ snd (rbtreeify_g n kvs) = kvs"
  1543 by(induction rule: rbtreeify_induct) simp_all
  1544 
  1545 lemma length_entries_rbtreeify_f:
  1546   "n \<le> length kvs \<Longrightarrow> length (entries (fst (rbtreeify_f n kvs))) = n"
  1547   and length_entries_rbtreeify_g: 
  1548   "n \<le> Suc (length kvs) \<Longrightarrow> length (entries (fst (rbtreeify_g n kvs))) = n - 1"
  1549 by(induct rule: rbtreeify_induct) simp_all
  1550 
  1551 lemma rbtreeify_f_conv_drop: 
  1552   "n \<le> length kvs \<Longrightarrow> snd (rbtreeify_f n kvs) = drop n kvs"
  1553 using entries_rbtreeify_f_append[of n kvs]
  1554 by(simp add: append_eq_conv_conj length_entries_rbtreeify_f)
  1555 
  1556 lemma rbtreeify_g_conv_drop: 
  1557   "n \<le> Suc (length kvs) \<Longrightarrow> snd (rbtreeify_g n kvs) = drop (n - 1) kvs"
  1558 using entries_rbtreeify_g_append[of n kvs]
  1559 by(simp add: append_eq_conv_conj length_entries_rbtreeify_g)
  1560 
  1561 lemma entries_rbtreeify_f [simp]:
  1562   "n \<le> length kvs \<Longrightarrow> entries (fst (rbtreeify_f n kvs)) = take n kvs"
  1563 using entries_rbtreeify_f_append[of n kvs]
  1564 by(simp add: append_eq_conv_conj length_entries_rbtreeify_f)
  1565 
  1566 lemma entries_rbtreeify_g [simp]:
  1567   "n \<le> Suc (length kvs) \<Longrightarrow> 
  1568   entries (fst (rbtreeify_g n kvs)) = take (n - 1) kvs"
  1569 using entries_rbtreeify_g_append[of n kvs]
  1570 by(simp add: append_eq_conv_conj length_entries_rbtreeify_g)
  1571 
  1572 lemma keys_rbtreeify_f [simp]: "n \<le> length kvs
  1573   \<Longrightarrow> keys (fst (rbtreeify_f n kvs)) = take n (map fst kvs)"
  1574 by(simp add: keys_def take_map)
  1575 
  1576 lemma keys_rbtreeify_g [simp]: "n \<le> Suc (length kvs)
  1577   \<Longrightarrow> keys (fst (rbtreeify_g n kvs)) = take (n - 1) (map fst kvs)"
  1578 by(simp add: keys_def take_map)
  1579 
  1580 lemma rbtreeify_fD: 
  1581   "\<lbrakk> rbtreeify_f n kvs = (t, kvs'); n \<le> length kvs \<rbrakk> 
  1582   \<Longrightarrow> entries t = take n kvs \<and> kvs' = drop n kvs"
  1583 using rbtreeify_f_conv_drop[of n kvs] entries_rbtreeify_f[of n kvs] by simp
  1584 
  1585 lemma rbtreeify_gD: 
  1586   "\<lbrakk> rbtreeify_g n kvs = (t, kvs'); n \<le> Suc (length kvs) \<rbrakk>
  1587   \<Longrightarrow> entries t = take (n - 1) kvs \<and> kvs' = drop (n - 1) kvs"
  1588 using rbtreeify_g_conv_drop[of n kvs] entries_rbtreeify_g[of n kvs] by simp
  1589 
  1590 lemma entries_rbtreeify [simp]: "entries (rbtreeify kvs) = kvs"
  1591 by(simp add: rbtreeify_def entries_rbtreeify_g)
  1592 
  1593 context linorder begin
  1594 
  1595 lemma rbt_sorted_rbtreeify_f: 
  1596   "\<lbrakk> n \<le> length kvs; sorted (map fst kvs); distinct (map fst kvs) \<rbrakk> 
  1597   \<Longrightarrow> rbt_sorted (fst (rbtreeify_f n kvs))"
  1598   and rbt_sorted_rbtreeify_g: 
  1599   "\<lbrakk> n \<le> Suc (length kvs); sorted (map fst kvs); distinct (map fst kvs) \<rbrakk>
  1600   \<Longrightarrow> rbt_sorted (fst (rbtreeify_g n kvs))"
  1601 proof(induction n kvs and n kvs rule: rbtreeify_induct)
  1602   case (f_even n kvs t k v kvs')
  1603   from rbtreeify_fD[OF `rbtreeify_f n kvs = (t, (k, v) # kvs')` `n \<le> length kvs`]
  1604   have "entries t = take n kvs"
  1605     and kvs': "drop n kvs = (k, v) # kvs'" by simp_all
  1606   hence unfold: "kvs = take n kvs @ (k, v) # kvs'" by(metis append_take_drop_id)
  1607   from `sorted (map fst kvs)` kvs'
  1608   have "(\<forall>(x, y) \<in> set (take n kvs). x \<le> k) \<and> (\<forall>(x, y) \<in> set kvs'. k \<le> x)"
  1609     by(subst (asm) unfold)(auto simp add: sorted_append sorted_Cons)
  1610   moreover from `distinct (map fst kvs)` kvs'
  1611   have "(\<forall>(x, y) \<in> set (take n kvs). x \<noteq> k) \<and> (\<forall>(x, y) \<in> set kvs'. x \<noteq> k)"
  1612     by(subst (asm) unfold)(auto intro: rev_image_eqI)
  1613   ultimately have "(\<forall>(x, y) \<in> set (take n kvs). x < k) \<and> (\<forall>(x, y) \<in> set kvs'. k < x)"
  1614     by fastforce
  1615   hence "fst (rbtreeify_f n kvs) |\<guillemotleft> k" "k \<guillemotleft>| fst (rbtreeify_g n kvs')"
  1616     using `n \<le> Suc (length kvs')` `n \<le> length kvs` set_take_subset[of "n - 1" kvs']
  1617     by(auto simp add: ord.rbt_greater_prop ord.rbt_less_prop take_map split_def)
  1618   moreover from `sorted (map fst kvs)` `distinct (map fst kvs)`
  1619   have "rbt_sorted (fst (rbtreeify_f n kvs))" by(rule f_even.IH)
  1620   moreover have "sorted (map fst kvs')" "distinct (map fst kvs')"
  1621     using `sorted (map fst kvs)` `distinct (map fst kvs)`
  1622     by(subst (asm) (1 2) unfold, simp add: sorted_append sorted_Cons)+
  1623   hence "rbt_sorted (fst (rbtreeify_g n kvs'))" by(rule f_even.IH)
  1624   ultimately show ?case
  1625     using `0 < n` `rbtreeify_f n kvs = (t, (k, v) # kvs')` by simp
  1626 next
  1627   case (f_odd n kvs t k v kvs')
  1628   from rbtreeify_fD[OF `rbtreeify_f n kvs = (t, (k, v) # kvs')` `n \<le> length kvs`]
  1629   have "entries t = take n kvs" 
  1630     and kvs': "drop n kvs = (k, v) # kvs'" by simp_all
  1631   hence unfold: "kvs = take n kvs @ (k, v) # kvs'" by(metis append_take_drop_id)
  1632   from `sorted (map fst kvs)` kvs'
  1633   have "(\<forall>(x, y) \<in> set (take n kvs). x \<le> k) \<and> (\<forall>(x, y) \<in> set kvs'. k \<le> x)"
  1634     by(subst (asm) unfold)(auto simp add: sorted_append sorted_Cons)
  1635   moreover from `distinct (map fst kvs)` kvs'
  1636   have "(\<forall>(x, y) \<in> set (take n kvs). x \<noteq> k) \<and> (\<forall>(x, y) \<in> set kvs'. x \<noteq> k)"
  1637     by(subst (asm) unfold)(auto intro: rev_image_eqI)
  1638   ultimately have "(\<forall>(x, y) \<in> set (take n kvs). x < k) \<and> (\<forall>(x, y) \<in> set kvs'. k < x)"
  1639     by fastforce
  1640   hence "fst (rbtreeify_f n kvs) |\<guillemotleft> k" "k \<guillemotleft>| fst (rbtreeify_f n kvs')"
  1641     using `n \<le> length kvs'` `n \<le> length kvs` set_take_subset[of n kvs']
  1642     by(auto simp add: rbt_greater_prop rbt_less_prop take_map split_def)
  1643   moreover from `sorted (map fst kvs)` `distinct (map fst kvs)`
  1644   have "rbt_sorted (fst (rbtreeify_f n kvs))" by(rule f_odd.IH)
  1645   moreover have "sorted (map fst kvs')" "distinct (map fst kvs')"
  1646     using `sorted (map fst kvs)` `distinct (map fst kvs)`
  1647     by(subst (asm) (1 2) unfold, simp add: sorted_append sorted_Cons)+
  1648   hence "rbt_sorted (fst (rbtreeify_f n kvs'))" by(rule f_odd.IH)
  1649   ultimately show ?case 
  1650     using `0 < n` `rbtreeify_f n kvs = (t, (k, v) # kvs')` by simp
  1651 next
  1652   case (g_even n kvs t k v kvs')
  1653   from rbtreeify_gD[OF `rbtreeify_g n kvs = (t, (k, v) # kvs')` `n \<le> Suc (length kvs)`]
  1654   have t: "entries t = take (n - 1) kvs" 
  1655     and kvs': "drop (n - 1) kvs = (k, v) # kvs'" by simp_all
  1656   hence unfold: "kvs = take (n - 1) kvs @ (k, v) # kvs'" by(metis append_take_drop_id)
  1657   from `sorted (map fst kvs)` kvs'
  1658   have "(\<forall>(x, y) \<in> set (take (n - 1) kvs). x \<le> k) \<and> (\<forall>(x, y) \<in> set kvs'. k \<le> x)"
  1659     by(subst (asm) unfold)(auto simp add: sorted_append sorted_Cons)
  1660   moreover from `distinct (map fst kvs)` kvs'
  1661   have "(\<forall>(x, y) \<in> set (take (n - 1) kvs). x \<noteq> k) \<and> (\<forall>(x, y) \<in> set kvs'. x \<noteq> k)"
  1662     by(subst (asm) unfold)(auto intro: rev_image_eqI)
  1663   ultimately have "(\<forall>(x, y) \<in> set (take (n - 1) kvs). x < k) \<and> (\<forall>(x, y) \<in> set kvs'. k < x)"
  1664     by fastforce
  1665   hence "fst (rbtreeify_g n kvs) |\<guillemotleft> k" "k \<guillemotleft>| fst (rbtreeify_g n kvs')"
  1666     using `n \<le> Suc (length kvs')` `n \<le> Suc (length kvs)` set_take_subset[of "n - 1" kvs']
  1667     by(auto simp add: rbt_greater_prop rbt_less_prop take_map split_def)
  1668   moreover from `sorted (map fst kvs)` `distinct (map fst kvs)`
  1669   have "rbt_sorted (fst (rbtreeify_g n kvs))" by(rule g_even.IH)
  1670   moreover have "sorted (map fst kvs')" "distinct (map fst kvs')"
  1671     using `sorted (map fst kvs)` `distinct (map fst kvs)`
  1672     by(subst (asm) (1 2) unfold, simp add: sorted_append sorted_Cons)+
  1673   hence "rbt_sorted (fst (rbtreeify_g n kvs'))" by(rule g_even.IH)
  1674   ultimately show ?case using `0 < n` `rbtreeify_g n kvs = (t, (k, v) # kvs')` by simp
  1675 next
  1676   case (g_odd n kvs t k v kvs')
  1677   from rbtreeify_fD[OF `rbtreeify_f n kvs = (t, (k, v) # kvs')` `n \<le> length kvs`]
  1678   have "entries t = take n kvs"
  1679     and kvs': "drop n kvs = (k, v) # kvs'" by simp_all
  1680   hence unfold: "kvs = take n kvs @ (k, v) # kvs'" by(metis append_take_drop_id)
  1681   from `sorted (map fst kvs)` kvs'
  1682   have "(\<forall>(x, y) \<in> set (take n kvs). x \<le> k) \<and> (\<forall>(x, y) \<in> set kvs'. k \<le> x)"
  1683     by(subst (asm) unfold)(auto simp add: sorted_append sorted_Cons)
  1684   moreover from `distinct (map fst kvs)` kvs'
  1685   have "(\<forall>(x, y) \<in> set (take n kvs). x \<noteq> k) \<and> (\<forall>(x, y) \<in> set kvs'. x \<noteq> k)"
  1686     by(subst (asm) unfold)(auto intro: rev_image_eqI)
  1687   ultimately have "(\<forall>(x, y) \<in> set (take n kvs). x < k) \<and> (\<forall>(x, y) \<in> set kvs'. k < x)"
  1688     by fastforce
  1689   hence "fst (rbtreeify_f n kvs) |\<guillemotleft> k" "k \<guillemotleft>| fst (rbtreeify_g n kvs')"
  1690     using `n \<le> Suc (length kvs')` `n \<le> length kvs` set_take_subset[of "n - 1" kvs']
  1691     by(auto simp add: rbt_greater_prop rbt_less_prop take_map split_def)
  1692   moreover from `sorted (map fst kvs)` `distinct (map fst kvs)`
  1693   have "rbt_sorted (fst (rbtreeify_f n kvs))" by(rule g_odd.IH)
  1694   moreover have "sorted (map fst kvs')" "distinct (map fst kvs')"
  1695     using `sorted (map fst kvs)` `distinct (map fst kvs)`
  1696     by(subst (asm) (1 2) unfold, simp add: sorted_append sorted_Cons)+
  1697   hence "rbt_sorted (fst (rbtreeify_g n kvs'))" by(rule g_odd.IH)
  1698   ultimately show ?case
  1699     using `0 < n` `rbtreeify_f n kvs = (t, (k, v) # kvs')` by simp
  1700 qed simp_all
  1701 
  1702 lemma rbt_sorted_rbtreeify: 
  1703   "\<lbrakk> sorted (map fst kvs); distinct (map fst kvs) \<rbrakk> \<Longrightarrow> rbt_sorted (rbtreeify kvs)"
  1704 by(simp add: rbtreeify_def rbt_sorted_rbtreeify_g)
  1705 
  1706 lemma is_rbt_rbtreeify: 
  1707   "\<lbrakk> sorted (map fst kvs); distinct (map fst kvs) \<rbrakk>
  1708   \<Longrightarrow> is_rbt (rbtreeify kvs)"
  1709 by(simp add: is_rbt_def rbtreeify_def inv1_rbtreeify_g inv2_rbtreeify_g rbt_sorted_rbtreeify_g color_of_rbtreeify_g)
  1710 
  1711 lemma rbt_lookup_rbtreeify:
  1712   "\<lbrakk> sorted (map fst kvs); distinct (map fst kvs) \<rbrakk> \<Longrightarrow> 
  1713   rbt_lookup (rbtreeify kvs) = map_of kvs"
  1714 by(simp add: map_of_entries[symmetric] rbt_sorted_rbtreeify)
  1715 
  1716 end
  1717 
  1718 text {* 
  1719   Functions to compare the height of two rbt trees, taken from 
  1720   Andrew W. Appel, Efficient Verified Red-Black Trees (September 2011)
  1721 *}
  1722 
  1723 fun skip_red :: "('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt"
  1724 where
  1725   "skip_red (Branch color.R l k v r) = l"
  1726 | "skip_red t = t"
  1727 
  1728 fun skip_black :: "('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt"
  1729 where
  1730   "skip_black (Branch color.B l k v r) = l"
  1731 | "skip_black t = t"
  1732 
  1733 datatype compare = LT | GT | EQ
  1734 
  1735 partial_function (tailrec) compare_height :: "('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt \<Rightarrow> compare"
  1736 where
  1737   "compare_height sx s t tx =
  1738   (case (skip_red sx, skip_red s, skip_red t, skip_red tx) of
  1739      (Branch _ sx' _ _ _, Branch _ s' _ _ _, Branch _ t' _ _ _, Branch _ tx' _ _ _) \<Rightarrow> 
  1740        compare_height (skip_black sx') s' t' (skip_black tx')
  1741    | (_, rbt.Empty, _, Branch _ _ _ _ _) \<Rightarrow> LT
  1742    | (Branch _ _ _ _ _, _, rbt.Empty, _) \<Rightarrow> GT
  1743    | (Branch _ sx' _ _ _, Branch _ s' _ _ _, Branch _ t' _ _ _, rbt.Empty) \<Rightarrow>
  1744        compare_height (skip_black sx') s' t' rbt.Empty
  1745    | (rbt.Empty, Branch _ s' _ _ _, Branch _ t' _ _ _, Branch _ tx' _ _ _) \<Rightarrow>
  1746        compare_height rbt.Empty s' t' (skip_black tx')
  1747    | _ \<Rightarrow> EQ)"
  1748 
  1749 declare compare_height.simps [code]
  1750 
  1751 hide_type (open) compare
  1752 hide_const (open)
  1753   compare_height skip_black skip_red LT GT EQ compare_case compare_rec 
  1754   Abs_compare Rep_compare compare_rep_set
  1755 hide_fact (open)
  1756   Abs_compare_cases Abs_compare_induct Abs_compare_inject Abs_compare_inverse
  1757   Rep_compare Rep_compare_cases Rep_compare_induct Rep_compare_inject Rep_compare_inverse
  1758   compare.simps compare.exhaust compare.induct compare.recs compare.simps
  1759   compare.size compare.case_cong compare.weak_case_cong compare.cases 
  1760   compare.nchotomy compare.split compare.split_asm compare_rec_def
  1761   compare.eq.refl compare.eq.simps
  1762   compare.EQ_def compare.GT_def compare.LT_def
  1763   equal_compare_def
  1764   skip_red_def skip_red.simps skip_red.induct 
  1765   skip_black_def skip_black.simps skip_black.induct
  1766   compare_height.simps
  1767 
  1768 subsection {* union and intersection of sorted associative lists *}
  1769 
  1770 context ord begin
  1771 
  1772 function sunion_with :: "('a \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list" 
  1773 where
  1774   "sunion_with f ((k, v) # as) ((k', v') # bs) =
  1775    (if k > k' then (k', v') # sunion_with f ((k, v) # as) bs
  1776     else if k < k' then (k, v) # sunion_with f as ((k', v') # bs)
  1777     else (k, f k v v') # sunion_with f as bs)"
  1778 | "sunion_with f [] bs = bs"
  1779 | "sunion_with f as [] = as"
  1780 by pat_completeness auto
  1781 termination by lexicographic_order
  1782 
  1783 function sinter_with :: "('a \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list \<Rightarrow> ('a \<times> 'b) list"
  1784 where
  1785   "sinter_with f ((k, v) # as) ((k', v') # bs) =
  1786   (if k > k' then sinter_with f ((k, v) # as) bs
  1787    else if k < k' then sinter_with f as ((k', v') # bs)
  1788    else (k, f k v v') # sinter_with f as bs)"
  1789 | "sinter_with f [] _ = []"
  1790 | "sinter_with f _ [] = []"
  1791 by pat_completeness auto
  1792 termination by lexicographic_order
  1793 
  1794 end
  1795 
  1796 declare ord.sunion_with.simps [code] ord.sinter_with.simps[code]
  1797 
  1798 context linorder begin
  1799 
  1800 lemma set_fst_sunion_with: 
  1801   "set (map fst (sunion_with f xs ys)) = set (map fst xs) \<union> set (map fst ys)"
  1802 by(induct f xs ys rule: sunion_with.induct) auto
  1803 
  1804 lemma sorted_sunion_with [simp]:
  1805   "\<lbrakk> sorted (map fst xs); sorted (map fst ys) \<rbrakk> 
  1806   \<Longrightarrow> sorted (map fst (sunion_with f xs ys))"
  1807 by(induct f xs ys rule: sunion_with.induct)
  1808   (auto simp add: sorted_Cons set_fst_sunion_with simp del: set_map)
  1809 
  1810 lemma distinct_sunion_with [simp]:
  1811   "\<lbrakk> distinct (map fst xs); distinct (map fst ys); sorted (map fst xs); sorted (map fst ys) \<rbrakk>
  1812   \<Longrightarrow> distinct (map fst (sunion_with f xs ys))"
  1813 proof(induct f xs ys rule: sunion_with.induct)
  1814   case (1 f k v xs k' v' ys)
  1815   have "\<lbrakk> \<not> k < k'; \<not> k' < k \<rbrakk> \<Longrightarrow> k = k'" by simp
  1816   thus ?case using "1"
  1817     by(auto simp add: set_fst_sunion_with sorted_Cons simp del: set_map)
  1818 qed simp_all
  1819 
  1820 lemma map_of_sunion_with: 
  1821   "\<lbrakk> sorted (map fst xs); sorted (map fst ys) \<rbrakk>
  1822   \<Longrightarrow> map_of (sunion_with f xs ys) k = 
  1823   (case map_of xs k of None \<Rightarrow> map_of ys k 
  1824   | Some v \<Rightarrow> case map_of ys k of None \<Rightarrow> Some v 
  1825               | Some w \<Rightarrow> Some (f k v w))"
  1826 by(induct f xs ys rule: sunion_with.induct)(auto simp add: sorted_Cons split: option.split dest: map_of_SomeD bspec)
  1827 
  1828 lemma set_fst_sinter_with [simp]:
  1829   "\<lbrakk> sorted (map fst xs); sorted (map fst ys) \<rbrakk>
  1830   \<Longrightarrow> set (map fst (sinter_with f xs ys)) = set (map fst xs) \<inter> set (map fst ys)"
  1831 by(induct f xs ys rule: sinter_with.induct)(auto simp add: sorted_Cons simp del: set_map)
  1832 
  1833 lemma set_fst_sinter_with_subset1:
  1834   "set (map fst (sinter_with f xs ys)) \<subseteq> set (map fst xs)"
  1835 by(induct f xs ys rule: sinter_with.induct) auto
  1836 
  1837 lemma set_fst_sinter_with_subset2:
  1838   "set (map fst (sinter_with f xs ys)) \<subseteq> set (map fst ys)"
  1839 by(induct f xs ys rule: sinter_with.induct)(auto simp del: set_map)
  1840 
  1841 lemma sorted_sinter_with [simp]:
  1842   "\<lbrakk> sorted (map fst xs); sorted (map fst ys) \<rbrakk>
  1843   \<Longrightarrow> sorted (map fst (sinter_with f xs ys))"
  1844 by(induct f xs ys rule: sinter_with.induct)(auto simp add: sorted_Cons simp del: set_map)
  1845 
  1846 lemma distinct_sinter_with [simp]:
  1847   "\<lbrakk> distinct (map fst xs); distinct (map fst ys) \<rbrakk>
  1848   \<Longrightarrow> distinct (map fst (sinter_with f xs ys))"
  1849 proof(induct f xs ys rule: sinter_with.induct)
  1850   case (1 f k v as k' v' bs)
  1851   have "\<lbrakk> \<not> k < k'; \<not> k' < k \<rbrakk> \<Longrightarrow> k = k'" by simp
  1852   thus ?case using "1" set_fst_sinter_with_subset1[of f as bs]
  1853     set_fst_sinter_with_subset2[of f as bs]
  1854     by(auto simp del: set_map)
  1855 qed simp_all
  1856 
  1857 lemma map_of_sinter_with:
  1858   "\<lbrakk> sorted (map fst xs); sorted (map fst ys) \<rbrakk>
  1859   \<Longrightarrow> map_of (sinter_with f xs ys) k = 
  1860   (case map_of xs k of None \<Rightarrow> None | Some v \<Rightarrow> Option.map (f k v) (map_of ys k))"
  1861 apply(induct f xs ys rule: sinter_with.induct)
  1862 apply(auto simp add: sorted_Cons Option.map_def split: option.splits dest: map_of_SomeD bspec)
  1863 done
  1864 
  1865 end
  1866 
  1867 lemma distinct_map_of_rev: "distinct (map fst xs) \<Longrightarrow> map_of (rev xs) = map_of xs"
  1868 by(induct xs)(auto 4 3 simp add: map_add_def intro!: ext split: option.split intro: rev_image_eqI)
  1869 
  1870 lemma map_map_filter: 
  1871   "map f (List.map_filter g xs) = List.map_filter (Option.map f \<circ> g) xs"
  1872 by(auto simp add: List.map_filter_def)
  1873 
  1874 lemma map_filter_option_map_const: 
  1875   "List.map_filter (\<lambda>x. Option.map (\<lambda>y. f x) (g (f x))) xs = filter (\<lambda>x. g x \<noteq> None) (map f xs)"
  1876 by(auto simp add: map_filter_def filter_map o_def)
  1877 
  1878 lemma set_map_filter: "set (List.map_filter P xs) = the ` (P ` set xs - {None})"
  1879 by(auto simp add: List.map_filter_def intro: rev_image_eqI)
  1880 
  1881 context ord begin
  1882 
  1883 definition rbt_union_with_key :: "('a \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt"
  1884 where
  1885   "rbt_union_with_key f t1 t2 =
  1886   (case RBT_Impl.compare_height t1 t1 t2 t2
  1887    of compare.EQ \<Rightarrow> rbtreeify (sunion_with f (entries t1) (entries t2))
  1888     | compare.LT \<Rightarrow> fold (rbt_insert_with_key (\<lambda>k v w. f k w v)) t1 t2
  1889     | compare.GT \<Rightarrow> fold (rbt_insert_with_key f) t2 t1)"
  1890 
  1891 definition rbt_union_with where
  1892   "rbt_union_with f = rbt_union_with_key (\<lambda>_. f)"
  1893 
  1894 definition rbt_union where
  1895   "rbt_union = rbt_union_with_key (%_ _ rv. rv)"
  1896 
  1897 definition rbt_inter_with_key :: "('a \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a, 'b) rbt"
  1898 where
  1899   "rbt_inter_with_key f t1 t2 =
  1900   (case RBT_Impl.compare_height t1 t1 t2 t2 
  1901    of compare.EQ \<Rightarrow> rbtreeify (sinter_with f (entries t1) (entries t2))
  1902     | compare.LT \<Rightarrow> rbtreeify (List.map_filter (\<lambda>(k, v). Option.map (\<lambda>w. (k, f k v w)) (rbt_lookup t2 k)) (entries t1))
  1903     | compare.GT \<Rightarrow> rbtreeify (List.map_filter (\<lambda>(k, v). Option.map (\<lambda>w. (k, f k w v)) (rbt_lookup t1 k)) (entries t2)))"
  1904 
  1905 definition rbt_inter_with where
  1906   "rbt_inter_with f = rbt_inter_with_key (\<lambda>_. f)"
  1907 
  1908 definition rbt_inter where
  1909   "rbt_inter = rbt_inter_with_key (\<lambda>_ _ rv. rv)"
  1910 
  1911 end
  1912 
  1913 context linorder begin
  1914 
  1915 lemma rbt_sorted_entries_right_unique:
  1916   "\<lbrakk> (k, v) \<in> set (entries t); (k, v') \<in> set (entries t); 
  1917      rbt_sorted t \<rbrakk> \<Longrightarrow> v = v'"
  1918 by(auto dest!: distinct_entries inj_onD[where x="(k, v)" and y="(k, v')"] simp add: distinct_map)
  1919 
  1920 lemma rbt_sorted_fold_rbt_insertwk:
  1921   "rbt_sorted t \<Longrightarrow> rbt_sorted (List.fold (\<lambda>(k, v). rbt_insert_with_key f k v) xs t)"
  1922 by(induct xs rule: rev_induct)(auto simp add: rbt_insertwk_rbt_sorted)
  1923 
  1924 lemma is_rbt_fold_rbt_insertwk:
  1925   assumes "is_rbt t1"
  1926   shows "is_rbt (fold (rbt_insert_with_key f) t2 t1)"
  1927 proof -
  1928   def xs \<equiv> "entries t2"
  1929   from assms show ?thesis unfolding fold_def xs_def[symmetric]
  1930     by(induct xs rule: rev_induct)(auto simp add: rbt_insertwk_is_rbt)
  1931 qed
  1932 
  1933 lemma rbt_lookup_fold_rbt_insertwk:
  1934   assumes t1: "rbt_sorted t1" and t2: "rbt_sorted t2"
  1935   shows "rbt_lookup (fold (rbt_insert_with_key f) t1 t2) k =
  1936   (case rbt_lookup t1 k of None \<Rightarrow> rbt_lookup t2 k
  1937    | Some v \<Rightarrow> case rbt_lookup t2 k of None \<Rightarrow> Some v
  1938                | Some w \<Rightarrow> Some (f k w v))"
  1939 proof -
  1940   def xs \<equiv> "entries t1"
  1941   hence dt1: "distinct (map fst xs)" using t1 by(simp add: distinct_entries)
  1942   with t2 show ?thesis
  1943     unfolding fold_def map_of_entries[OF t1, symmetric]
  1944       xs_def[symmetric] distinct_map_of_rev[OF dt1, symmetric]
  1945     apply(induct xs rule: rev_induct)
  1946     apply(auto simp add: rbt_lookup_rbt_insertwk rbt_sorted_fold_rbt_insertwk split: option.splits)
  1947     apply(auto simp add: distinct_map_of_rev intro: rev_image_eqI)
  1948     done
  1949 qed
  1950 
  1951 lemma is_rbt_rbt_unionwk [simp]:
  1952   "\<lbrakk> is_rbt t1; is_rbt t2 \<rbrakk> \<Longrightarrow> is_rbt (rbt_union_with_key f t1 t2)"
  1953 by(simp add: rbt_union_with_key_def Let_def is_rbt_fold_rbt_insertwk is_rbt_rbtreeify rbt_sorted_entries distinct_entries split: compare.split)
  1954 
  1955 lemma rbt_lookup_rbt_unionwk:
  1956   "\<lbrakk> rbt_sorted t1; rbt_sorted t2 \<rbrakk> 
  1957   \<Longrightarrow> rbt_lookup (rbt_union_with_key f t1 t2) k = 
  1958   (case rbt_lookup t1 k of None \<Rightarrow> rbt_lookup t2 k 
  1959    | Some v \<Rightarrow> case rbt_lookup t2 k of None \<Rightarrow> Some v 
  1960               | Some w \<Rightarrow> Some (f k v w))"
  1961 by(auto simp add: rbt_union_with_key_def Let_def rbt_lookup_fold_rbt_insertwk rbt_sorted_entries distinct_entries map_of_sunion_with map_of_entries rbt_lookup_rbtreeify split: option.split compare.split)
  1962 
  1963 lemma rbt_unionw_is_rbt: "\<lbrakk> is_rbt lt; is_rbt rt \<rbrakk> \<Longrightarrow> is_rbt (rbt_union_with f lt rt)"
  1964 by(simp add: rbt_union_with_def)
  1965 
  1966 lemma rbt_union_is_rbt: "\<lbrakk> is_rbt lt; is_rbt rt \<rbrakk> \<Longrightarrow> is_rbt (rbt_union lt rt)"
  1967 by(simp add: rbt_union_def)
  1968 
  1969 lemma rbt_lookup_rbt_union:
  1970   "\<lbrakk> rbt_sorted s; rbt_sorted t \<rbrakk> \<Longrightarrow>
  1971   rbt_lookup (rbt_union s t) = rbt_lookup s ++ rbt_lookup t"
  1972 by(rule ext)(simp add: rbt_lookup_rbt_unionwk rbt_union_def map_add_def split: option.split)
  1973 
  1974 lemma rbt_interwk_is_rbt [simp]:
  1975   "\<lbrakk> rbt_sorted t1; rbt_sorted t2 \<rbrakk> \<Longrightarrow> is_rbt (rbt_inter_with_key f t1 t2)"
  1976 by(auto simp add: rbt_inter_with_key_def Let_def map_map_filter split_def o_def option_map_comp map_filter_option_map_const sorted_filter[where f=id, simplified] rbt_sorted_entries distinct_entries intro: is_rbt_rbtreeify split: compare.split)
  1977 
  1978 lemma rbt_interw_is_rbt:
  1979   "\<lbrakk> rbt_sorted t1; rbt_sorted t2 \<rbrakk> \<Longrightarrow> is_rbt (rbt_inter_with f t1 t2)"
  1980 by(simp add: rbt_inter_with_def)
  1981 
  1982 lemma rbt_inter_is_rbt:
  1983   "\<lbrakk> rbt_sorted t1; rbt_sorted t2 \<rbrakk> \<Longrightarrow> is_rbt (rbt_inter t1 t2)"
  1984 by(simp add: rbt_inter_def)
  1985 
  1986 lemma rbt_lookup_rbt_interwk:
  1987   "\<lbrakk> rbt_sorted t1; rbt_sorted t2 \<rbrakk>
  1988   \<Longrightarrow> rbt_lookup (rbt_inter_with_key f t1 t2) k =
  1989   (case rbt_lookup t1 k of None \<Rightarrow> None 
  1990    | Some v \<Rightarrow> case rbt_lookup t2 k of None \<Rightarrow> None
  1991                | Some w \<Rightarrow> Some (f k v w))"
  1992 by(auto 4 3 simp add: rbt_inter_with_key_def Let_def map_of_entries[symmetric] rbt_lookup_rbtreeify map_map_filter split_def o_def option_map_comp map_filter_option_map_const sorted_filter[where f=id, simplified] rbt_sorted_entries distinct_entries map_of_sinter_with map_of_eq_None_iff set_map_filter split: option.split compare.split intro: rev_image_eqI dest: rbt_sorted_entries_right_unique)
  1993 
  1994 lemma rbt_lookup_rbt_inter:
  1995   "\<lbrakk> rbt_sorted t1; rbt_sorted t2 \<rbrakk>
  1996   \<Longrightarrow> rbt_lookup (rbt_inter t1 t2) = rbt_lookup t2 |` dom (rbt_lookup t1)"
  1997 by(auto simp add: rbt_inter_def rbt_lookup_rbt_interwk restrict_map_def split: option.split)
  1998 
  1999 end
  2000 
  2001 
  2002 subsection {* Code generator setup *}
  2003 
  2004 lemmas [code] =
  2005   ord.rbt_less_prop
  2006   ord.rbt_greater_prop
  2007   ord.rbt_sorted.simps
  2008   ord.rbt_lookup.simps
  2009   ord.is_rbt_def
  2010   ord.rbt_ins.simps
  2011   ord.rbt_insert_with_key_def
  2012   ord.rbt_insertw_def
  2013   ord.rbt_insert_def
  2014   ord.rbt_del_from_left.simps
  2015   ord.rbt_del_from_right.simps
  2016   ord.rbt_del.simps
  2017   ord.rbt_delete_def
  2018   ord.sunion_with.simps
  2019   ord.sinter_with.simps
  2020   ord.rbt_union_with_key_def
  2021   ord.rbt_union_with_def
  2022   ord.rbt_union_def
  2023   ord.rbt_inter_with_key_def
  2024   ord.rbt_inter_with_def
  2025   ord.rbt_inter_def
  2026   ord.rbt_map_entry.simps
  2027   ord.rbt_bulkload_def
  2028 
  2029 text {* More efficient implementations for @{term entries} and @{term keys} *}
  2030 
  2031 definition gen_entries :: 
  2032   "(('a \<times> 'b) \<times> ('a, 'b) rbt) list \<Rightarrow> ('a, 'b) rbt \<Rightarrow> ('a \<times> 'b) list"
  2033 where
  2034   "gen_entries kvts t = entries t @ concat (map (\<lambda>(kv, t). kv # entries t) kvts)"
  2035 
  2036 lemma gen_entries_simps [simp, code]:
  2037   "gen_entries [] Empty = []"
  2038   "gen_entries ((kv, t) # kvts) Empty = kv # gen_entries kvts t"
  2039   "gen_entries kvts (Branch c l k v r) = gen_entries (((k, v), r) # kvts) l"
  2040 by(simp_all add: gen_entries_def)
  2041 
  2042 lemma entries_code [code]:
  2043   "entries = gen_entries []"
  2044 by(simp add: gen_entries_def fun_eq_iff)
  2045 
  2046 definition gen_keys :: "('a \<times> ('a, 'b) rbt) list \<Rightarrow> ('a, 'b) rbt \<Rightarrow> 'a list"
  2047 where "gen_keys kts t = RBT_Impl.keys t @ concat (List.map (\<lambda>(k, t). k # keys t) kts)"
  2048 
  2049 lemma gen_keys_simps [simp, code]:
  2050   "gen_keys [] Empty = []"
  2051   "gen_keys ((k, t) # kts) Empty = k # gen_keys kts t"
  2052   "gen_keys kts (Branch c l k v r) = gen_keys ((k, r) # kts) l"
  2053 by(simp_all add: gen_keys_def)
  2054 
  2055 lemma keys_code [code]:
  2056   "keys = gen_keys []"
  2057 by(simp add: gen_keys_def fun_eq_iff)
  2058 
  2059 text {* Restore original type constraints for constants *}
  2060 setup {*
  2061   fold Sign.add_const_constraint
  2062     [(@{const_name rbt_less}, SOME @{typ "('a :: order) \<Rightarrow> ('a, 'b) rbt \<Rightarrow> bool"}),
  2063      (@{const_name rbt_greater}, SOME @{typ "('a :: order) \<Rightarrow> ('a, 'b) rbt \<Rightarrow> bool"}),
  2064      (@{const_name rbt_sorted}, SOME @{typ "('a :: linorder, 'b) rbt \<Rightarrow> bool"}),
  2065      (@{const_name rbt_lookup}, SOME @{typ "('a :: linorder, 'b) rbt \<Rightarrow> 'a \<rightharpoonup> 'b"}),
  2066      (@{const_name is_rbt}, SOME @{typ "('a :: linorder, 'b) rbt \<Rightarrow> bool"}),
  2067      (@{const_name rbt_ins}, SOME @{typ "('a\<Colon>linorder \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2068      (@{const_name rbt_insert_with_key}, SOME @{typ "('a\<Colon>linorder \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2069      (@{const_name rbt_insert_with}, SOME @{typ "('b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> ('a :: linorder) \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2070      (@{const_name rbt_insert}, SOME @{typ "('a :: linorder) \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2071      (@{const_name rbt_del_from_left}, SOME @{typ "('a\<Colon>linorder) \<Rightarrow> ('a,'b) rbt \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2072      (@{const_name rbt_del_from_right}, SOME @{typ "('a\<Colon>linorder) \<Rightarrow> ('a,'b) rbt \<Rightarrow> 'a \<Rightarrow> 'b \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2073      (@{const_name rbt_del}, SOME @{typ "('a\<Colon>linorder) \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2074      (@{const_name rbt_delete}, SOME @{typ "('a\<Colon>linorder) \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2075      (@{const_name rbt_union_with_key}, SOME @{typ "('a\<Colon>linorder \<Rightarrow> 'b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2076      (@{const_name rbt_union_with}, SOME @{typ "('b \<Rightarrow> 'b \<Rightarrow> 'b) \<Rightarrow> ('a\<Colon>linorder,'b) rbt \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2077      (@{const_name rbt_union}, SOME @{typ "('a\<Colon>linorder,'b) rbt \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2078      (@{const_name rbt_map_entry}, SOME @{typ "'a\<Colon>linorder \<Rightarrow> ('b \<Rightarrow> 'b) \<Rightarrow> ('a,'b) rbt \<Rightarrow> ('a,'b) rbt"}),
  2079      (@{const_name rbt_bulkload}, SOME @{typ "('a \<times> 'b) list \<Rightarrow> ('a\<Colon>linorder,'b) rbt"})]
  2080 *}
  2081 
  2082 hide_const (open) R B Empty entries keys fold gen_keys gen_entries
  2083 
  2084 end