# 《Two Dozen Short Lessons in Haskell》（二十一）在形式参数中使用模式匹配

### 第二十一章 Patterns as Formal Parameters

1 The formula (x : xs) is equivalent to

a x ++ xs

b [x] ++ xs

c [x] ++ [xs]

d all of the above

2 The definition

HASKELL DEFINITION • f(x : xs) = g x xs

HASKELL DEFINITION • f [ ] = h

a defines h in terms of g

b defines f for arguments that are either empty or non-empty sequences

c will not work if xs is the empty sequence

d all of the above

3 The definition

HASKELL DEFINITION • f(x : xs) = g x xs

is equivalent to

a f xs | null xs = g x xs

b f xs = g x xs || h

c f xs | not(null xs) = g (head x) (tail xs)

d f x xs = g(x : xs)

4 Which of the following defines a function of type ([Char], Char) -> [Char] ?

a f( (x : xs), ’x’ ) = [x] ++ reverse xs ++ [’x’]

b f( x , y : ys ) = [ ] ++ reverse ys ++ [x]

c f( (xs : ’x’), x ) = [x] ++ reverse xs ++ [’x’]

d all of the above

5 Which of the following formulas delivers every third element of the sequence xs?

a foldr drop [ ] xs

b [ foldr drop [ ] suffix | suffix <- iterate (drop 3) xs ]

c [ x | (x : suffix) <- takeWhile (/= [ ]) (iterate (drop 3) (drop 2 xs)) ]

d takeWhile (/= [ ]) (iterate (take 3) xs)

=============================

=============================

1 b

2 b

3 c

4 a

b选项不仅仅应用于([Char],Char)，还可以应用于其它类型，f :: (a, [a]) -> [a]

c中的(xs:’x’)应该是无法匹配的，根据reverse xs ++ [’x’]，可以推断xs是[Char]，这样(xs:’x’)里的'x’就应该是[[Char]]类型，所以会报语法错。

5 c

posted @ 2013-05-27 18:07  申龙斌的程序人生  阅读(881)  评论(0编辑  收藏  举报