Exercise 7.3


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.)


One response to “Exercise 7.3”

  1. 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 Reply

Your email address will not be published. Required fields are marked *