Skip to content

Instantly share code, notes, and snippets.

@gilesbradshaw
Last active October 30, 2015 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilesbradshaw/3cba32655ec2b38be604 to your computer and use it in GitHub Desktop.
Save gilesbradshaw/3cba32655ec2b38be604 to your computer and use it in GitHub Desktop.
Tree
-- making and searching a binary search tree in haskell
data Tree a = EmptyTree | Node a (Tree a) (Tree a) deriving (Show)
singleton :: a -> Tree a
singleton x = Node x EmptyTree EmptyTree
treeInsert :: (Ord a) => a -> Tree a -> Tree a
treeInsert x EmptyTree = singleton x
treeInsert x (Node a left right)
| x == a = Node x left right
| x < a = Node a (treeInsert x left) right
| x > a = Node a left (treeInsert x right)
treeElem :: (Ord a) => a -> Tree a -> Bool
treeElem x EmptyTree = False
treeElem x (Node a left right)
| x == a = True
| x < a = treeElem x left
| x > a = treeElem x right
instance Functor Tree where
fmap f EmptyTree = EmptyTree
fmap f (Node x left right) = Node (f x) (fmap f left) (fmap f right)
-- then to make one we could fold over a list
newBinaryTree = foldr treeInsert EmptyTree [0,2..1000]
treeElem 5 newBinaryTree
-- False
treeElem 56 newBinaryTree
-- True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment