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