Ref:http://typedef.me/blog/2011/01/25/real_world_haskell_solutions_chapter_3/
Exercises on P.60
1. Write the converse of fromList for the List type: a function that takes a List a and generates a [a].
- -- file: ch03/ListADT.hs
-
data List a = Cons a (List a)
-
| Nil
-
deriving (Show)
-
-
fromList (x:xs) = Cons x (fromList xs)
-
fromList [] = Nil
-
-
-
toList (Cons x xs) = x: (toList xs)
-
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.
- -- file:ch03/tree.hs
-
--data Tree a = Node a (Tree a) (Tree a)
-
-- | Empty
-
-- deriving (Show)
-
-
data Tree a = Node a (Maybe (Tree a)) (Maybe (Tree a))
-
deriving (Show)
Exercises on P. 69-70
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.
- -- file ch03/myLength.hs
-
-
myLength :: [a] -> Int
-
myLength (x:xs) = if null xs
-
then 1
-
else 1 + myLength xs
-
myLength _ = 0
-
-
myLength2 [] = 0
-
myLength2 (_:xs) = 1 + myLength2 xs
-
-
-
myLength3 :: [a] -> Int
-
myLength3 (x:xs)
-
| null xs = 1
-
| otherwise = 1 + myLength3 xs
-
myLength3 _ = 0
3. Write a function that computes the mean of a list.
- -- file: ch03/myMean.hs
-
myMean :: [Double] -> Double
-
myMean xs = if null xs
-
then 0
-
else mySum xs / fromIntegral (length xs)
-
-
mySum :: [Double] -> Double
-
mySum (x:xs) = x + mySum xs
-
mySum [] = 0
4. Turn a list into a palindrome; i.e., it should read the same both backward and forward.
- -- file:ch03/myPalindrome.hs
-
myPalindrome :: [Int]-> [Int]
-
myPalindrome (x:xs) = [x] ++ (myPalindrome xs) ++ [x]
-
myPalindrome [] = []
阅读(544) | 评论(0) | 转发(0) |