Quellcode durchsuchen

add a simple red black tree implementation.

doesn't have update, delete, union or anything, but it seems to insert
ok.
Lucas Stadler vor 11 Jahren
Ursprung
Commit
2a6b0ae11b
1 geänderte Dateien mit 58 neuen und 0 gelöschten Zeilen
  1. 58 0
      hs/DataStructures.hs

+ 58 - 0
hs/DataStructures.hs

@ -267,3 +267,61 @@ instance Queue FingerTree where
267 267
    dequeue ft =
268 268
        case last ft of
269 269
            Just x -> Just (x, rest ft) -- broken, we'd need a different version of rest
270
271
class Associative as where
272
    get :: (Ord k) => k -> as k v -> Maybe v
273
274
    insert :: (Ord k) => k -> v -> as k v -> as k v
275
276
    --update :: k -> v -> as k v -> as k v
277
278
    -- intersect :: as k v -> as k v -> as k v
279
    -- union :: as k v -> as k v
280
281
    empty :: as k v
282
283
-- examples
284
rb = fromPairs $ zip [1..10] [2..11] :: RBTree Int Int
285
286
fromPairs :: (Associative as, Ord k) => [(k, v)] -> as k v
287
fromPairs [] = empty
288
fromPairs ((k, v):kvs) = insert k v $ fromPairs kvs
289
290
data RBTree k v =
291
      RBLeaf Color -- always Black
292
    | RBNode {
293
          color :: Color,
294
          left :: RBTree k v,
295
          key :: k, value :: v,
296
          right :: RBTree k v
297
      } deriving Show
298
299
data Color = Red | Black deriving Show
300
301
balance :: (Ord k) => Color -> RBTree k v -> k -> v -> RBTree k v -> RBTree k v
302
balance Black (RBNode Red (RBNode Red a xk xv b) yk yv c) zk zv d =
303
    RBNode Red (RBNode Black a xk xv b) yk yv (RBNode Black c zk zv d)
304
balance Black (RBNode Red a xk xv (RBNode Red b yk yv c)) zk zv d =
305
    RBNode Black (RBNode Red a xk xv b) yk yv (RBNode Black c zk zv d)
306
balance Black a xk xv (RBNode Red (RBNode Red b yk yv c) zk zv d) =
307
    RBNode Black (RBNode Red a xk xv b) yk yv (RBNode Black c zk zv d)
308
balance Black a xk xv (RBNode Red b yk yv (RBNode Red c zk zv d)) =
309
    RBNode Black (RBNode Red a xk xv b) yk yv (RBNode Black c zk zv d)
310
balance c l k v r = RBNode c l k v r
311
312
instance Associative RBTree where
313
    get ik (RBLeaf _) = Nothing
314
    get ik (RBNode c l k v r) | k == ik = Just v
315
    get ik (RBNode c l k v r) =
316
        if k > ik
317
        then get ik l
318
        else get ik r
319
320
    insert ik iv (RBLeaf c) =
321
        RBNode Red (RBLeaf Black) ik iv (RBLeaf Black)
322
    insert ik iv (RBNode c l k v r) =
323
        if k > ik
324
        then balance c (insert ik iv l) k v r
325
        else balance c l k v (insert ik iv r)
326
327
    empty = RBLeaf Black