Programming in Haskell Chapter1 Exercises Solutions

Programming in Haskell是一本入门Haskell的好书,介绍页面以及配套的slides, vedios, codes都在这里


给出double (double 2)的另外一种可能解释。

书上给的例子是应用序和正则序(从左向右),可以将正则序(从右向左)当作答案。

1
2
3
4
5
6
7
double (double 2)
= double 2 + double 2
= double 2 + (2 + 2)
= double 2 + 4
= (2 + 2) + 4
= 4 + 4
= 8

解释sum [x]的求值过程。

sum的定义:

1
2
sum [] = 0
sum (x:xs) = x + sum xs

sum [x] 求值过程:

1
2
3
4
sum [x]
= x + sum []
= x + 0
= x

定义product

仿照sum的定义,将product定义如下:

1
2
product []     = 1
product (x:xs) = x * sum xs

product [2, 3, 4]求值过程:

1
2
3
4
5
6
product [2,3,4]
= 2 * product [3, 4]
= 2 * 3 * product [4]
= 2 * 3 * 4 * product []
= 2 * 3 * 4 * 1
= 24

qsort改成输出倒序的。

将课本中的例子larger和smaller交换即可。

1
2
3
4
5
6
7
8
9
10
-- qsort.hs
qsort [] = []
qsort (x:xs) = qsort larger ++ [x] ++ qsort smaller
where
larger = [a | a <- xs, a > x]
smaller = [b | b <- xs, b <= x]


--- *Main> qsort [3,5,1,4,2]
--- [5,4,3,2,1]

qsort定义中的<=换成<会如何。

若将<=换成<,则与x相等的元素将会丢失。

1
2
*Main> qsort [2,2,3,3,1]
[3,3,2,1]
1
this