SOE ex.7.3


data InternalTree a = ILeaf
                    | IBranch a (InternalTree a) (InternalTree a)
  deriving Show

treeFold :: (a -> b -> b -> b) -> b -> InternalTree a -> b
treeFold f init ILeaf = init
treeFold f init (IBranch a lt rt) = f a leftResult rightResult
  where leftResult  = treeFold f init lt
        rightResult = treeFold f init rt

treeRepeat :: a -> InternalTree a
treeRepeat x = IBranch x (treeRepeat x) (treeRepeat x)

----- some tests -----

t :: InternalTree Integer
t  = IBranch 1                        --           1
       (IBranch 2 ILeaf ILeaf)        --         /   \
       (IBranch 3                     --        2     3
         (IBranch 4                   --       / \   /  \
            (IBranch 5 ILeaf ILeaf)   --      -  -  4    6
            (ILeaf))                  --           / \  / \
         (IBranch 6 ILeaf ILeaf))     --          5   - -  -
                                      --         / \
                                      --        -   -

treeSum   = treeFold (\node lv rv -> node+lv+rv) 0
inorder   = treeFold (\node lv rv -> lv++[node]++rv) []
preorder  = treeFold (\node lv rv -> [node]++lv++rv) []
postorder = treeFold (\node lv rv -> lv++rv++[node]) []

main = do
  putStrLn $ show $ treeSum   t
  putStrLn $ show $ inorder   t
  putStrLn $ show $ preorder  t
  putStrLn $ show $ postorder t
  putStrLn $ show $ takeTree  3  (treeRepeat 'A')

{- takeTree from ex.7.2 -}
takeTree :: Int -> InternalTree a -> InternalTree a
takeTree 0 _ = ILeaf
takeTree _ ILeaf = ILeaf
takeTree (n+1) (IBranch a lt rt) = IBranch a (takeTree n lt) (takeTree n rt)

Leave a Reply