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)
This entry was posted
on Wednesday, May 23rd, 2007 at 4:36 pm and is filed under Haskell - SOE.
You can follow any responses to this entry through the RSS 2.0 feed.
You can leave a response, or trackback from your own site.