2

I defined my own Data Type BinTree, which describes my binary trees:

data BinTree a = Empty | Node a (BinTree a) (BinTree a) deriving (Show,Eq)

After that I implemented three sort-functions for the binary trees: preorder, inorder and postorder:

preorder :: BinTree a -> [a]
preorder Empty = []
preorder (Node x lt rt) = [x] ++ preorder lt ++ preorder rt

inorder :: BinTree  a -> [a]
inorder Empty = []
inorder (Node x lt rt) = inorder lt ++ [x] ++ inorder rt

postorder :: BinTree a -> [a]
postorder Empty = []
postorder (Node x lt rt) = postorder lt ++ postorder rt ++ [x]

To improve my order-functions, I implemented the foldTree function (which works as a normal foldr function, but with binary trees):

foldTree :: (a -> b -> b -> b) -> b -> BinTree -> b
    foldTree f e Empty = e
    foldTree f e (Node x lt rt) = f x (foldTree f e lt) (foldTree f e rt)

And now I got stuck, because I cant't figure out how to combine the order-functions with the foldTree.

Can someone give me a hint please?

Will Ness
  • 70,110
  • 9
  • 98
  • 181
Theresa
  • 65
  • 5

1 Answers1

0

If by "combine" you mean implement each of the three functions using the last one, then this my recent answer seems to be of use, e.g.

preorder  t  =  foldTree (\a l r -> (a :) . l . r) id t []
inorder   t  =  foldTree (\a l r -> l . (a :) . r) id t []
postorder t  =  foldTree (\a l r -> l . r . (a :)) id t []

Trying it out:

> t = Node 1 (Node 2 Empty (Node 3 Empty Empty)) (Node 4 (Node 5 Empty Empty) Empty)
{-
                 1
        2                 4
     .      3         5       .
          .   .     .   .
-}

> inorder t
[2,3,1,5,4]

> preorder t
[1,2,3,4,5]

> postorder t
[3,2,5,4,1]

The correct type of your function is, of course,

foldTree :: (a -> b -> b -> b) -> b -> BinTree a -> b
--                                            ^^^
Will Ness
  • 70,110
  • 9
  • 98
  • 181