theory BSTInCLass imports Main begin datatype tree = Tip | Node tree nat tree thm tree.induct primrec is_BST :: "tree => nat => nat => bool" where "is_BST Tip lo hi = True" | "is_BST (Node l x r) lo hi = (lo <= x & x <= hi & is_BST l lo x & is_BST r x hi)" primrec insert :: "tree => nat => tree" where "insert Tip x = Node Tip x Tip" | "insert (Node l y r) x = (if x < y then Node (insert l x) y r else if y < x then Node l y (insert r x) else Node l y r)" primrec in_tree :: "tree => nat => bool" where "in_tree Tip x = False" | "in_tree (Node l y r) x = (x = y | in_tree l x | in_tree r x)" theorem "in_tree (insert t x) y = (in_tree t y | x = y)" apply (induct t) apply force apply force done lemma insert_left: "[| is_BST t lo hi; x < lo; lo <= hi |] ==> is_BST (insert t x) x hi" apply (induct t arbitrary: lo hi x) apply auto done lemma insert_mid: "[| is_BST t lo hi; lo <= x; x <= hi; lo <= hi |] ==> is_BST (insert t x) lo hi" apply (induct t arbitrary: lo hi x) apply auto done lemma insert_right: "[| is_BST t lo hi; hi < x; lo <= hi |] ==> is_BST (insert t x) lo x" apply (induct t arbitrary: lo hi x) apply auto done theorem "[| is_BST t lo hi; lo <= hi |] ==> is_BST (insert t x) (min lo x) (max x hi)" apply (case_tac "x < lo") using insert_left[of t lo hi x] apply arith apply (case_tac "x <= hi") using insert_mid[of t lo hi x] apply arith using insert_right[of t lo hi x] apply arith done -- "Think of lookup as an optimized version of in_tree." primrec lookup :: "tree => nat => bool" where "lookup Tip x = False" | "lookup (Node left y right) x = (if x < y then lookup left x else if y < x then lookup right x else True)" lemma lookup_implies_in_tree: "\ is_BST t lo hi; lookup t x \ \ in_tree t x" apply (induct t arbitrary: lo hi) apply simp apply auto apply (case_tac "nat < lo") apply auto apply (case_tac "hi < nat") apply auto apply (case_tac "x < nat") apply auto done end