1(* Author: Tobias Nipkow *) 2 3section \<open>Unbalanced Tree Implementation of Set\<close> 4 5theory Tree_Set 6imports 7 "HOL-Library.Tree" 8 Cmp 9 Set_Specs 10begin 11 12definition empty :: "'a tree" where 13"empty == Leaf" 14 15fun isin :: "'a::linorder tree \<Rightarrow> 'a \<Rightarrow> bool" where 16"isin Leaf x = False" | 17"isin (Node l a r) x = 18 (case cmp x a of 19 LT \<Rightarrow> isin l x | 20 EQ \<Rightarrow> True | 21 GT \<Rightarrow> isin r x)" 22 23hide_const (open) insert 24 25fun insert :: "'a::linorder \<Rightarrow> 'a tree \<Rightarrow> 'a tree" where 26"insert x Leaf = Node Leaf x Leaf" | 27"insert x (Node l a r) = 28 (case cmp x a of 29 LT \<Rightarrow> Node (insert x l) a r | 30 EQ \<Rightarrow> Node l a r | 31 GT \<Rightarrow> Node l a (insert x r))" 32 33fun split_min :: "'a tree \<Rightarrow> 'a * 'a tree" where 34"split_min (Node l a r) = 35 (if l = Leaf then (a,r) else let (x,l') = split_min l in (x, Node l' a r))" 36 37fun delete :: "'a::linorder \<Rightarrow> 'a tree \<Rightarrow> 'a tree" where 38"delete x Leaf = Leaf" | 39"delete x (Node l a r) = 40 (case cmp x a of 41 LT \<Rightarrow> Node (delete x l) a r | 42 GT \<Rightarrow> Node l a (delete x r) | 43 EQ \<Rightarrow> if r = Leaf then l else let (a',r') = split_min r in Node l a' r')" 44 45 46subsection "Functional Correctness Proofs" 47 48lemma isin_set: "sorted(inorder t) \<Longrightarrow> isin t x = (x \<in> set (inorder t))" 49by (induction t) (auto simp: isin_simps) 50 51lemma inorder_insert: 52 "sorted(inorder t) \<Longrightarrow> inorder(insert x t) = ins_list x (inorder t)" 53by(induction t) (auto simp: ins_list_simps) 54 55 56lemma split_minD: 57 "split_min t = (x,t') \<Longrightarrow> t \<noteq> Leaf \<Longrightarrow> x # inorder t' = inorder t" 58by(induction t arbitrary: t' rule: split_min.induct) 59 (auto simp: sorted_lems split: prod.splits if_splits) 60 61lemma inorder_delete: 62 "sorted(inorder t) \<Longrightarrow> inorder(delete x t) = del_list x (inorder t)" 63by(induction t) (auto simp: del_list_simps split_minD split: prod.splits) 64 65interpretation S: Set_by_Ordered 66where empty = empty and isin = isin and insert = insert and delete = delete 67and inorder = inorder and inv = "\<lambda>_. True" 68proof (standard, goal_cases) 69 case 1 show ?case by (simp add: empty_def) 70next 71 case 2 thus ?case by(simp add: isin_set) 72next 73 case 3 thus ?case by(simp add: inorder_insert) 74next 75 case 4 thus ?case by(simp add: inorder_delete) 76qed (rule TrueI)+ 77 78end 79