Skip to content

Instantly share code, notes, and snippets.

@googya
Created December 6, 2017 10:08
Show Gist options
  • Select an option

  • Save googya/30aa5befeac9a4d4836cf41d80fea3fc to your computer and use it in GitHub Desktop.

Select an option

Save googya/30aa5befeac9a4d4836cf41d80fea3fc to your computer and use it in GitHub Desktop.
module BinaryTree where
data BinaryTree a =
Leaf
| Node (BinaryTree a ) a (BinaryTree a)
deriving (Eq, Ord, Show)
insert' :: Ord a => a -> BinaryTree a -> BinaryTree a
insert' b Leaf = Node Leaf b Leaf
insert' b (Node left a right)
| b == a = Node left a right
| b < a = Node (insert' b left) a right
| b > a = Node left a (insert' b right)
mapTree :: (a -> b) -> BinaryTree a -> BinaryTree b
mapTree _ Leaf = Leaf
mapTree f (Node left a right) =
Node (mapTree f left) (f a) (mapTree f right)
testTree' :: BinaryTree Integer
testTree' =
Node (Node Leaf 3 Leaf ) 1 (Node Leaf 4 Leaf)
mapExpected =
Node (Node Leaf 4 Leaf) 2 (Node Leaf 5 Leaf)
mapOkay =
if mapTree (+1) testTree' == mapExpected
then print "yup okay"
else error "test failed!"
preorder :: BinaryTree a -> [a]
preorder Leaf = []
preorder (Node left a right) = [a] ++ (preorder left) ++ (preorder right)
inorder :: BinaryTree a -> [a]
inorder Leaf = []
inorder (Node left a right) = (inorder left) ++ [a] ++ (inorder right)
postorder :: BinaryTree a -> [a]
postorder Leaf = []
postorder (Node left a right) = (postorder left) ++ (postorder right) ++ [a]
testTree :: BinaryTree Integer
testTree = Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 Leaf)
testPreorder :: IO ()
testPreorder =
if preorder testTree == [2,1,3]
then putStrLn "Preorder fine!"
else putStrLn "Bad news bears."
testInorder :: IO ()
testInorder =
if inorder testTree == [1,2,3]
then putStrLn "Inorder fine!"
else putStrLn "Bad news bears."
testPostorder :: IO ()
testPostorder =
if postorder testTree == [1,3,2]
then putStrLn "Postorder fine!"
else putStrLn "Bad news bears."
-- foldTree :: (a -> b -> b) -> b -> BinaryTree a -> b
-- foldTree _ _ Leaf = []
-- foldTree f b (Node left a right) = fold (\x y -> f x
f :: Show a => (a, b) -> IO (a, b)
f t@(a, _) = do
print a
return t
doubleUp :: [a] -> [a]
doubleUp [] = []
doubleUp xs@(x:_) = x:xs
-- isSubsequenceOf "blah" "blahwoot"
-- isSubsequenceOf "blah" "wootblah"
isSubsequenceOf :: (Eq a) => [a] -> [a] -> Bool
isSubsequenceOf _ [] = False
isSubsequenceOf [] _ = True
isSubsequenceOf orig@(x1:xs1) (x2:xs2) =
if (x1 == x2) then (isSubsequenceOf xs1 xs2)
else isSubsequenceOf orig xs2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment