My answers to the exercises of chapter 3.
Page 60:
1. Write the converse of fromList for the List type: a function that takes a List a and generates a [a].
toList :: List a -> [a]
toList (Cons x y) = x : toList y
toList Nil = []
2. Define a tree type that has only one constructor, like our Java example. Instead of the Empty constructor, use the Maybe type to refer to a node’s children.
data Tree a = Node a (Maybe (Tree a)) (Maybe (Tree a))
deriving (Show)
Page 69:
1. Write a function that computes the number of elements in a list. To test it, ensure that it gives the same answers as the standard length function.
myLength [] = 0
myLength (x:xs) = 1 + myLength xs
2. Add a type signature for your function to your source file. To test it, load the source file into ghci again.
myLength :: [a] -> Integer
myLength [] = 0
myLength (x:xs) = 1 + myLength xs
3. Write a function that computes the mean of a list, i.e. the sum of all elements in the list divided by its length. (You may need to use the fromIntegral function to convert the length of the list from an integer into a floating point number.)
mean xs = sum xs / fromIntegral (length xs)
4. Turn a list into a palindrome, i.e. it should read the same both backwards and forwards. For example, given the list [1,2,3], your function should return [1,2,3,3,2,1].
palindrome xs = xs ++ reverse xs
5. Write a function that determines whether its input list is a palindrome.
isPalindrome xs = xs == reverse xs
6. Create a function that sorts a list of lists based on the length of each sublist. (You may want to look at the sortBy function from the Data.List module.)
sortByLength xss = sortBy cmpLength xss
where
cmpLength = xs ys -> compare (length xs) (length ys)
Or, less bulky, using the on function from the Data.Function module.
sortByLength' = sortBy (compare `on` length)
7. Define a function that joins a list of lists together using a separator value.
intersperse :: a -> [[a]] -> [a]
intersperse _ [] = []
intersperse _ (xs:[]) = xs
intersperse s (xs:xss) = xs ++ [s] ++ (intersperse s xss)
8. Using the binary tree type that we defined earlier in this chapter, write a function that will determine the height of the tree. The height is the largest number of hops from the root to an Empty. For example, the tree Empty has height zero; Node "x" Empty Empty has height one; Node "x" Empty (Node "y" Empty Empty) has height two; and so on.
height :: Tree a -> Integer
height (Node _ x y) = 1 + max (height x) (height y)
height Empty = 0
9. Consider three two-dimensional points a, b, and c. If we look at the angle formed by the line segment from a to b and the line segment from b to c, it either turns left, turns right, or forms a straight line. Define a Direction data type that lets you represent these possibilities.
data Direction = LeftTurn
| RightTurn
| Straight
deriving (Show)