Skip to content
Snippets Groups Projects
BinTree.hs 1.31 KiB
Newer Older
Martin Ring's avatar
Martin Ring committed
data Tree a = Leaf a | Node (Tree a) (Tree a)    

data Ctxt a = Empty 
            | Le (Ctxt a) (Tree a)
            | Ri (Tree a) (Ctxt a)

newtype Loc a = Loc (Tree a, Ctxt a)  

top :: Tree a-> Loc a
top t = (Loc (t, Empty))

go_left :: Loc a-> Loc a
go_left (Loc(t, ctx)) = case ctx of
 Empty  -> error "go_left at empty"
 Le c r -> error "go_left of left"
 Ri l c -> Loc(l, Le c t)

go_right :: Loc a-> Loc a
go_right (Loc(t, ctx)) = case ctx of
 Empty  -> error "go_right at empty"
 Le c r -> Loc(r, Ri t c)
 Ri _ _ -> error "go_right of right"

go_up :: Loc a-> Loc a
go_up (Loc(t, ctx)) = case ctx of
  Empty  -> error "go_up of empty"
  Le c r -> Loc(Node t r, c)
  Ri l c -> Loc(Node l t, c)

go_down_left :: Loc a-> Loc a
go_down_left (Loc(t, c)) = case t of
  Leaf _   -> error "go_down at leaf"
  Node l r -> Loc(l, Le c r)

go_down_right :: Loc a-> Loc a
go_down_right (Loc(t, c)) = case t of
  Leaf _   -> error "go_down at leaf"
  Node l r -> Loc(r, Ri l c)

ins_left :: Tree a-> Loc a-> Loc a
ins_left t1 (Loc(t, ctx)) = Loc(t, Ri t1 ctx)

ins_right :: Tree a-> Loc a-> Loc a
ins_right t1 (Loc(t, ctx)) = Loc(t, Le ctx t1)

delete :: Loc a-> Loc a
delete (Loc(_, c)) = case c of
  Empty  -> error "delete of empty"
  Le c r -> Loc(r, c)
  Ri l c -> Loc(l, c)

update :: Tree a-> Loc a-> Loc a
update t (Loc(_, c)) = Loc(t, c)