Skip to content

Instantly share code, notes, and snippets.

@bitwombat
Created July 15, 2019 09:14
Show Gist options
  • Save bitwombat/e19af662550dec07dff2fd7ced3bd1fc to your computer and use it in GitHub Desktop.
Save bitwombat/e19af662550dec07dff2fd7ced3bd1fc to your computer and use it in GitHub Desktop.
Solutions to Page442 exercise of HPFFP
module Page442 where
data BinaryTree a =
Leaf
| Node (BinaryTree a) a (BinaryTree a)
deriving (Eq, Ord, Show)
preorder :: BinaryTree a -> [a]
preorder Leaf = []
preorder (Node left val right) = [val] ++ (preorder left) ++ (preorder right)
inorder :: BinaryTree a -> [a]
inorder Leaf = []
inorder (Node left val right) = (inorder left) ++ [val] ++ (inorder right)
postorder :: BinaryTree a -> [a]
postorder Leaf = []
postorder (Node left val right) = (postorder left) ++ (postorder right) ++ [val]
testTree :: BinaryTree Integer
testTree =
Node (Node (Node Leaf 1 Leaf) 2 (Node Leaf 3 Leaf))
4
(Node Leaf 8 (Node Leaf 23 Leaf))
testPreorder :: IO ()
testPreorder =
if preorder testTree == [4, 2, 1, 3, 8, 23]
then putStrLn "Preorder fine!"
else putStrLn "Preorder sad"
testInorder :: IO ()
testInorder =
if inorder testTree == [1, 2, 3, 4, 8, 23]
then putStrLn "Inorder fine!"
else putStrLn "Inorder sad"
testPostorder :: IO ()
testPostorder =
if postorder testTree == [1, 3, 2, 23, 8, 4]
then putStrLn "Postorder fine!"
else putStrLn "Postorder sad"
main :: IO ()
main = do
testPreorder
testInorder
testPostorder
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment