Skip to content

Instantly share code, notes, and snippets.

@BRonen
Last active June 3, 2023 14:50
Show Gist options
  • Save BRonen/1938ecceb262eeff96a41a8784e4f27d to your computer and use it in GitHub Desktop.
Save BRonen/1938ecceb262eeff96a41a8784e4f27d to your computer and use it in GitHub Desktop.
A binary tree implemented in haskell just for fun
module Main where
data Tree a = Leaf a | Node (Tree a) (Tree a)
stringifyTree :: Tree Integer -> [Char]
stringifyTree (Leaf x) = show x
stringifyTree (Node left right) = " {" ++ (stringifyTree left) ++ "} - {" ++ (stringifyTree right) ++ "} "
dump :: Tree a -> [a]
dump (Leaf x) = [x]
dump (Node left right) = dump left ++ dump right
halfLength :: [a] -> Int
halfLength xs = div (length xs) 2
parseTree :: [a] -> Tree a
parseTree [x] = Leaf x
parseTree xs = Node (parseTree left) (parseTree right)
where
(left, right) = splitAt (halfLength xs) xs
findMin :: Tree a -> a
findMin (Leaf x) = x
findMin (Node (Leaf x) _) = x
findMin (Node a _) = findMin a
findMax :: Tree a -> a
findMax (Leaf y) = y
findMax (Node _ (Leaf y)) = y
findMax (Node _ b) = findMax b
insertTree :: Ord a => Tree a -> a -> Tree a
insertTree (Leaf x) y
| x < y = Node (Leaf x) (Leaf y)
| x > y = Node (Leaf y) (Leaf x)
| otherwise = Leaf x
insertTree x@(Node a b) y
| y < findMin x = Node (Leaf y) (Node a b)
| y > findMax x = Node (Node a b) (Leaf y)
| y > findMax a = Node a (insertTree b y)
| y < findMin b = Node (insertTree a y) b
| otherwise = Node a b
arr :: [Integer]
arr = [1, 3, 4, 13]
main :: IO ()
main = do
print(dump(parseTree arr))
print (stringifyTree ( insertTree (parseTree arr) 5))
print (dump ( insertTree (parseTree arr) 5))
print (stringifyTree ( insertTree (parseTree arr) 8))
print (dump ( insertTree (parseTree arr) 8))
print (stringifyTree ( insertTree (parseTree arr) 0))
print (dump ( insertTree (parseTree arr) 0))
print (stringifyTree ( insertTree (parseTree arr) 16))
print (dump ( insertTree (parseTree arr) 16))
print (stringifyTree ( insertTree (parseTree arr) 17))
print (dump ( insertTree (parseTree arr) 17))
let tree = parseTree arr in
print (stringifyTree ( foldl insertTree tree [14, 0, 5, 2, 8, 17, 18, 17]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment