5

我一直在玩 Haskell 中的 RB 树实现,但很难稍微改变它,所以数据只放在叶子中,就像在二叉叶树中一样:

    /+\
   /   \
 /+\    \
/   \    c
a   b

除了节点的颜色之外,内部节点还将保存其他信息,例如树的大小(就像在正常的 RB 树中一样,但数据仅保存在叶子中)。我也不需要对插入的数据进行排序。我在插入数据时仅使用 RB 来获得平衡树,但我想保持插入数据的顺序。

原始代码是(来自冈崎书):

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

我将其更改为:(导致异常:函数 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

原来的平衡函数是:

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

从我上面的代码中可以明显看出,我做了一些改变。

提前感谢您的帮助:)

编辑:对于我正在寻找的那种表示,Chris Okasaki 建议我使用二进制随机访问列表,如他的书中所述。另一种方法是简单地调整 Data.Set 中的代码,它被实现为权重平衡树。

4

1 回答 1

1

假设您的意思是insert :: a -> Tree a -> Tree a,那么您的错误可能源于没有 for 子句ins (Leaf a)

于 2011-06-09T20:23:47.903 回答