section \<open>Association List Update and Deletion\<close>
theory AList_Upd_Del imports Sorted_Less begin
abbreviation"sorted1 ps \ sorted(map fst ps)"
text\<open>Define own \<open>map_of\<close> function to avoid pulling in an unknown
amount of lemmas implicitly (via the simpset).\<close>
hide_const (open) map_of
fun map_of :: "('a*'b)list \ 'a \ 'b option" where "map_of [] = (\x. None)" | "map_of ((a,b)#ps) = (\x. if x=a then Some b else map_of ps x)"
text\<open>Updating an association list:\<close>
fun upd_list :: "'a::linorder \ 'b \ ('a*'b) list \ ('a*'b) list" where "upd_list x y [] = [(x,y)]" | "upd_list x y ((a,b)#ps) =
(if x < a then (x,y)#(a,b)#ps else if x = a then (x,y)#ps else (a,b) # upd_list x y ps)"
fun del_list :: "'a::linorder \ ('a*'b)list \ ('a*'b)list" where "del_list x [] = []" | "del_list x ((a,b)#ps) = (if x = a then ps else (a,b) # del_list x ps)"
subsection \<open>Lemmas for \<^const>\<open>map_of\<close>\<close>
lemma map_of_ins_list: "map_of (upd_list x y ps) = (map_of ps)(x := Some y)" by(induction ps) auto
lemma map_of_append: "map_of (ps @ qs) x =
(case map_of ps x of None \<Rightarrow> map_of qs x | Some y \<Rightarrow> Some y)" by(induction ps)(auto)
subsection \<open>Lemmas for \<^const>\<open>upd_list\<close>\<close>
lemma sorted_upd_list: "sorted1 ps \ sorted1 (upd_list x y ps)" apply(induction ps) apply simp apply(case_tac ps) apply auto done
lemma upd_list_sorted: "sorted1 (ps @ [(a,b)]) \
upd_list x y (ps @ (a,b) # qs) =
(if x < a then upd_list x y ps @ (a,b) # qs
else ps @ upd_list x y ((a,b) # qs))" by(induction ps) (auto simp: sorted_lems)
text\<open>In principle, @{thm upd_list_sorted} suffices, but the following two
corollaries speed up proofs.\<close>
corollary upd_list_sorted1: "\ sorted (map fst ps @ [a]); x < a \ \
upd_list x y (ps @ (a,b) # qs) = upd_list x y ps @ (a,b) # qs" by (auto simp: upd_list_sorted)
corollary upd_list_sorted2: "\ sorted (map fst ps @ [a]); a \ x \ \
upd_list x y (ps @ (a,b) # qs) = ps @ upd_list x y ((a,b) # qs)" by (auto simp: upd_list_sorted)