问题
I've been playing around with RB tree implementation in Haskell but having difficulty changing it a bit so the data is only placed in the leaves, like in a binary leaf tree:
/+\
/ \
/+\ \
/ \ c
a b
The internal nodes would hold other information e.g. size of tree, in addition to the color of the node (like in a normal RB tree but the data is held in the leaves ony). I am also not needed to sort the data being inserted. I use RB only to get a balanced tree as i insert data but I want to keep the order in which data is inserted.
The original code was (from Okasaki book):
data Color = R | B
data Tree a = E | T Color (Tree a ) a (Tree a)
insert :: Ord a => a -> Tree a -> Tree a
insert x s = makeBlack (ins s)
where ins E = T R E x E
ins (T color a y b)
| x < y = balance color (ins a) y b
| x == y = T color a y b
| x > y = balance color a y (ins b)
makeBlack (T _ a y b) = T B a y b
I changed it to: (causing Exception:Non-exhaustive patterns in function ins)
data Color = R | B deriving Show
data Tree a = E | Leaf a | T Color Int (Tree a) (Tree a)
insert :: Ord a => a -> Set a -> Set a
insert x s = makeBlack (ins s)
where
ins E = T R 1 (Leaf x) E
ins (T _ 1 a E) = T R 2 (Leaf x) a
ins (T color y a b)
| 0 < y = balance color y (ins a) b
| 0 == y = T color y a b
| 0 > y = balance color y a (ins b)
makeBlack (T _ y a b) = T B y a b
The original balance function is:
balance B (T R (T R a x b) y c) z d = T R (T B a x b) y (T B c z d)
balance B (T R a x (T R b y c)) z d = T R (T B a x b) y (T B c z d)
balance B a x (T R (T R b y c) z d) = T R (T B a x b) y (T B c z d)
balance B a x (T R b y (T R c z d)) = T R (T B a x b) y (T B c z d)
balance color a x b = T color a x b
which i changed a bit as is obvious from my code above.
Thanks in advance for help :)
EDIT: for the kind of representation I'm looking, Chris Okasaki has suggested I use the binary random access list, as described in his book. An alternative would be to simply adapt the code in Data.Set, which is implemented as weight balanced trees.
回答1:
Assuming you meant insert :: a -> Tree a -> Tree a
, then your error probably stems from having no clause for ins (Leaf a)
.
来源:https://stackoverflow.com/questions/6238007/can-i-represent-a-red-black-tree-as-binary-leaf-tree