Exercise 7.2

data InternalTree a = ILeaf
                    | IBranch a (InternalTree a) (InternalTree a)
                      deriving Show
 
takeTree :: Int -> InternalTree a -> InternalTree a
takeTree 0 t = ILeaf
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

(Technical error 13 applies to this exercise.)

One Response to “Exercise 7.2”

  1. Ricky Liu says:

    I think _ should be used when pattern matching the ILeaf cases:

    takeTree 0 _ = ILeaf
    takeTree _ ILeaf = ILeaf
    takeTree n (IBranch x t1 t2) = IBranch x (takeTree (n-1) t1) (takeTree (n-1) t2)

    takeTreeWhile _ ILeaf = ILeaf
    takeTreeWhile pred (IBranch x t1 t2)
    | pred x = IBranch x (takeTreeWhile pred t1)
    (takeTreeWhile pred t2)
    | otherwise = ILeaf

    Also, guard can be used instead of if expression in takeTreeWhile.

Leave a Reply