07.28.07

Exercise 7.3

Posted in Uncategorized at 9:48 pm by admin

foldrTree :: (a -> b -> b) -> b -> InternalTree a -> b
foldrTree f z ILeaf = z
foldrTree f z (IBranch a x y) = foldrTree f (f a (foldrTree f z y)) x
 
foldlTree :: (a -> b -> a) -> a -> InternalTree b -> a
foldlTree f z ILeaf = z
foldlTree f z (IBranch a x y) = foldlTree f (f (foldlTree f z x) a) y
 
repeatTree :: a -> InternalTree a
repeatTree a = t
    where t = (IBranch a (t) (t))

repeatTree is apparently magic: the base case constructor (ILeaf) is not specified. But the takeTree and takeTreeWhile functions work with repeatTree as expected.

(Technical error 14 applies to this exercise.)

1 Comment »

  1. fero said,

    July 19, 2008 at 6:35 am

    Hi, repeatTree is no magic. I thought it as well first but look at definitions of takeTree and takeTreeWhile, pattern can actually match IBranch but returns ILeaf.

    takeTree :: Int -> InternalTree a -> InternalTree a
    takeTree 0 t = ILeaf — LOOK AT THIS
    takeTree n ILeaf = ILeaf
    takeTree n (IBranch a x y) = IBranch a (takeTree (n-1) x) (takeTree (n-1) y)

    takeTreeWhile :: (a -> Bool) -> InternalTree a -> InternalTree a
    takeTreeWhile f ILeaf = ILeaf
    takeTreeWhile f (IBranch a x y) = if (f a)
    then IBranch a (takeTreeWhile f x)
    (takeTreeWhile f y)
    else ILeaf — LOOK AT THIS

Leave a Comment