61203
|
1 |
(* Author: Tobias Nipkow *)
|
|
2 |
|
|
3 |
section {* Tree Implementation of Sets *}
|
|
4 |
|
|
5 |
theory Tree_Set
|
|
6 |
imports
|
|
7 |
"~~/src/HOL/Library/Tree"
|
|
8 |
Set_by_Ordered
|
|
9 |
begin
|
|
10 |
|
|
11 |
fun isin :: "'a::linorder tree \<Rightarrow> 'a \<Rightarrow> bool" where
|
|
12 |
"isin Leaf x = False" |
|
|
13 |
"isin (Node l a r) x = (x < a \<and> isin l x \<or> x=a \<or> isin r x)"
|
|
14 |
|
|
15 |
hide_const (open) insert
|
|
16 |
|
|
17 |
fun insert :: "'a::linorder \<Rightarrow> 'a tree \<Rightarrow> 'a tree" where
|
|
18 |
"insert a Leaf = Node Leaf a Leaf" |
|
|
19 |
"insert a (Node l x r) =
|
|
20 |
(if a < x then Node (insert a l) x r
|
|
21 |
else if a=x then Node l x r
|
|
22 |
else Node l x (insert a r))"
|
|
23 |
|
|
24 |
fun del_min :: "'a tree \<Rightarrow> 'a * 'a tree" where
|
|
25 |
"del_min (Node Leaf a r) = (a, r)" |
|
|
26 |
"del_min (Node l a r) = (let (x,l') = del_min l in (x, Node l' a r))"
|
|
27 |
|
|
28 |
fun delete :: "'a::linorder \<Rightarrow> 'a tree \<Rightarrow> 'a tree" where
|
|
29 |
"delete k Leaf = Leaf" |
|
|
30 |
"delete k (Node l a r) = (if k<a then Node (delete k l) a r else
|
|
31 |
if k > a then Node l a (delete k r) else
|
|
32 |
if r = Leaf then l else let (a',r') = del_min r in Node l a' r')"
|
|
33 |
|
|
34 |
|
|
35 |
subsection "Functional Correctness Proofs"
|
|
36 |
|
|
37 |
lemma "sorted(inorder t) \<Longrightarrow> isin t x = (x \<in> elems (inorder t))"
|
|
38 |
by (induction t) (auto simp: elems_simps)
|
|
39 |
|
|
40 |
lemma isin_set: "sorted(inorder t) \<Longrightarrow> isin t x = (x \<in> elems (inorder t))"
|
|
41 |
by (induction t) (auto simp: elems_simps0 dest: sortedD)
|
|
42 |
|
|
43 |
|
|
44 |
lemma inorder_insert:
|
|
45 |
"sorted(inorder t) \<Longrightarrow> inorder(insert x t) = ins_list x (inorder t)"
|
|
46 |
by(induction t) (auto simp: ins_simps)
|
|
47 |
|
|
48 |
|
|
49 |
lemma del_minD:
|
|
50 |
"del_min t = (x,t') \<Longrightarrow> t \<noteq> Leaf \<Longrightarrow> sorted(inorder t) \<Longrightarrow>
|
|
51 |
x # inorder t' = inorder t"
|
|
52 |
by(induction t arbitrary: t' rule: del_min.induct)
|
|
53 |
(auto simp: sorted_lems split: prod.splits)
|
|
54 |
|
|
55 |
lemma inorder_delete:
|
|
56 |
"sorted(inorder t) \<Longrightarrow> inorder(delete x t) = del_list x (inorder t)"
|
|
57 |
by(induction t) (auto simp: del_simps del_minD split: prod.splits)
|
|
58 |
|
|
59 |
|
|
60 |
interpretation Set_by_Ordered
|
|
61 |
where empty = Leaf and isin = isin and insert = insert and delete = delete
|
|
62 |
and inorder = inorder and wf = "\<lambda>_. True"
|
|
63 |
proof (standard, goal_cases)
|
|
64 |
case 1 show ?case by simp
|
|
65 |
next
|
|
66 |
case 2 thus ?case by(simp add: isin_set)
|
|
67 |
next
|
|
68 |
case 3 thus ?case by(simp add: inorder_insert)
|
|
69 |
next
|
|
70 |
case 4 thus ?case by(simp add: inorder_delete)
|
|
71 |
next
|
|
72 |
case 5 thus ?case by(simp)
|
|
73 |
qed
|
|
74 |
|
|
75 |
end
|