3 // Version 1, 'untyped'
6 deriving instance Show Color
8 data RB a = E | T Color (RB a) a (RB a)
10 rbToList :: RB a -> [a]
12 rbToList (T _ l a r) = rbToList l + [a] + rbToList r
14 deriving instance (Show a) => Show (RB a)
16 // Insertion and membership test as by Okasaki
17 insert :: Ord a => a -> RB a -> RB a
18 insert x s = (match ins s with T _ a z b -> T B a z b)
24 then balance (ins a) y b
26 then balance a y (ins b)
35 member :: Ord a => a -> RB a -> Boolean
42 // balance: first equation is new, to make it work with a weaker invariant
43 balance :: RB a -> a -> RB a -> RB a
44 balance (T R a x b) y (T R c z d) = T R (T B a x b) y (T B c z d)
45 balance (T R (T R a x b) y c) z d = T R (T B a x b) y (T B c z d)
46 balance (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d)
47 balance a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d)
48 balance a x (T R (T R b y c) z d) = T R (T B a x b) y (T B c z d)
49 balance a x b = T B a x b
52 delete :: Ord a => a -> RB a -> RB a
53 delete x t = (match del t with
54 T _ a y b -> T B a y b
59 | x<y = delformLeft a y b
60 | x>y = delformRight a y b
62 delformLeft a y b= match a with
63 T B _ _ _ -> balleft (del a) y b
65 delformRight a y b = match b with
66 T B _ _ _ -> balright a y (del b)
69 balleft :: RB a -> a -> RB a -> RB a
70 balleft (T R a x b) y c = T R (T B a x b) y c
71 balleft bl x (T B a y b) = balance bl x (T R a y b)
72 balleft bl x (T R (T B a y b) z c) = T R (T B bl x a) y (balance b z (sub1 c))
74 balright :: RB a -> a -> RB a -> RB a
75 balright a x (T R b y c) = T R a x (T B b y c)
76 balright (T B a x b) y bl = balance (T R a x b) y bl
77 balright (T R a x (T B b y c)) z bl = T R (balance (sub1 a) x b) y (T B c z bl)
80 sub1 (T B a x b) = T R a x b
81 sub1 _ = fail "invariance violation"
83 app :: RB a -> RB a -> RB a
86 app (T R a x b) (T R c y d) =
88 T R b' z c' -> T R(T R a x b') z (T R c' y d)
89 bc -> T R a x (T R bc y d)
90 app (T B a x b) (T B c y d) =
92 T R b' z c' -> T R(T B a x b') z (T B c' y d)
93 bc -> balleft a x (T B bc y d)
94 app a (T R b x c) = T R (app a b) x c
95 app (T R a x b) c = T R a x (app b c)
97 testList = [4,6,2,7,4,7,2,5]
99 main = rbToList (foldl (flip insert) E testList)