Created
July 10, 2011 02:17
-
-
Save axman6/1074170 to your computer and use it in GitHub Desktop.
Binary tree that allows lazy reading from disk (if used with bytestring-mmap)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data BTree a | |
= Null | |
| Leaf a | |
| Node a (BTree a) (BTree a) | |
deriving (Show) | |
-- makeTree :: [a] -> BTree a | |
-- makeTree xs = | |
instance Binary a => Binary (BTree a) where | |
put Null = putWord8 0 | |
put (Leaf a) = putWord8 1 >> put a | |
put (Node a l r) = do | |
putWord8 2 | |
put a | |
put (encode l) | |
put r | |
get = do | |
w <- getWord8 | |
case w of | |
0 -> return Null | |
1 -> fmap Leaf get | |
2 -> do | |
x <- get | |
ls <- get | |
r <- get | |
return (Node x (decode ls) r) | |
empty :: BTree a | |
empty = Null | |
insert :: Ord a => BTree a -> a -> BTree a | |
insert Null x = Leaf x | |
insert l@(Leaf y) x = | |
case x `compare` y of | |
LT -> Node y (Leaf x) Null | |
GT -> Node y Null (Leaf x) | |
EQ -> l | |
insert n@(Node y l r) x = | |
case x `compare` y of | |
LT -> Node y (insert l x) r | |
GT -> Node y l (insert r x) | |
EQ -> n | |
toList :: BTree a -> [a] | |
toList t = go t [] | |
where | |
go Null xs = xs | |
go (Leaf x) xs = x:xs | |
go (Node x l r) xs = go l $ x : go r xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment