Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222457
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: Python/Ruby

2011-06-07 10:21:00

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].
  1. -- file: ch03/ListADT.hs
  2. data List a = Cons a (List a)
  3.      | Nil
  4.      deriving (Show)

  5. fromList (x:xs) = Cons x (fromList xs)
  6. fromList [] = Nil


  7. toList (Cons x xs) = x: (toList xs)
  8. 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.
  1. -- file:ch03/tree.hs
  2. --data Tree a = Node a (Tree a) (Tree a)
  3. --     | Empty
  4. --     deriving (Show)

  5. data Tree a = Node a (Maybe (Tree a)) (Maybe (Tree a))
  6.              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.

  1. -- file ch03/myLength.hs

  2. myLength :: [a] -> Int
  3. myLength (x:xs) = if null xs
  4.                 then 1
  5.         else 1 + myLength xs
  6. myLength _ = 0

  7. myLength2 [] = 0
  8. myLength2 (_:xs) = 1 + myLength2 xs


  9. myLength3 :: [a] -> Int
  10. myLength3 (x:xs)
  11.            | null xs = 1
  12.         | otherwise = 1 + myLength3 xs
  13. myLength3 _ = 0

3. Write a function that computes the mean of a list.
  1. -- file: ch03/myMean.hs
  2. myMean :: [Double] -> Double
  3. myMean xs = if null xs
  4.                then 0
  5.         else mySum xs / fromIntegral (length xs)

  6. mySum :: [Double] -> Double
  7. mySum (x:xs) = x + mySum xs
  8. mySum [] = 0
4. Turn a list into a palindrome; i.e., it should read the same both backward and forward.

  1. -- file:ch03/myPalindrome.hs
  2. myPalindrome :: [Int]-> [Int]
  3. myPalindrome (x:xs) = [x] ++ (myPalindrome xs) ++ [x]
  4. myPalindrome [] = []


阅读(544) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~