module Lib where data Tree a = Leaf | Node (Left a) a (Right a) deriving (Show, Eq) type Left = Tree type Right = Tree type Update a = Tree a -> Tree a instance Foldable Tree where foldMap _ Leaf = mempty foldMap f (Node l a r) = mappend (mappend (foldMap f l) (f a)) (foldMap f r) insert :: Ord a => a -> Update a insert a Leaf = Node Leaf a Leaf insert a t@(Node l a' r) = case compare a a' of LT -> Node (insert a l) a' r EQ -> t GT -> Node l a' (insert a r) contains :: Ord a => Tree a -> (a -> Bool) contains Leaf _ = False contains (Node l a' r) a = case compare a a' of LT -> l `contains` a EQ -> True GT -> r `contains` a delete :: Ord a => a -> Update a delete a Leaf = Leaf delete a (Node l a' r) = case compare a a' of LT -> Node (delete a l) a' r EQ -> l `union` r GT -> Node l a' (delete a r) union :: Ord a => Tree a -> Tree a -> Tree a union = foldr insert