Skip to content

Instantly share code, notes, and snippets.

@davidkaste
Last active April 26, 2022 16:55
Show Gist options
  • Save davidkaste/c4a6d2a557840bbddaa0294dab7a169d to your computer and use it in GitHub Desktop.
Save davidkaste/c4a6d2a557840bbddaa0294dab7a169d to your computer and use it in GitHub Desktop.
Haskell binary search tree
module BinTree where
data BinTree a = Leaf
| Node (BinTree a) a (BinTree a)
instance Show a => Show (Tree a) where
show Leaf = "Leaf"
show (Node lt x rt) = "(" ++ show lt ++ " " ++ show x ++ " " ++ show rt ++ ")"
-- Tree is a Functor
instance Functor BinTree where
-- fmap :: (a -> b) -> f a -> f b
fmap f Leaf = Leaf
fmap f (Node lt x rt) = Node (fmap f lt) (f x) (fmap f rt)
-- Tree is an Applicative Functor
instance Applicative BinTree where
-- pure :: a -> f a
-- (<*>) :: f (a -> b) -> f a -> f b
pure x = Node Leaf x Leaf
Leaf <*> _ = Leaf
_ <*> Leaf = Leaf
(Node lf f rf) <*> (Node lt x rt) = Node (lf <*> lt) (f x) (rf <*> rt)
-- tree functions
insertTree :: (Ord a, Eq a) => a -> BinTree a -> BinTree a
insertTree a Leaf = Node Leaf a Leaf
insertTree a (Node lt x rt)
| a == x = Node lt a rt
| a < x = Node (insertTree a lt) x rt
| a > x = Node lt x (insertTree a rt)
searchTree :: (Eq a, Ord a) => a -> BinTree a -> Bool
searchTree a Leaf = False
searchTree a (Node lt x rt)
| a == x = True
| a < x = searchTree a lt
| a > x = searchTree a rt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment