《Two Dozen Short Lessons in Haskell》学习（十六）- Definitions with Alternatives

第16章 带条件分支的函数定义

1 Guards in function definitions

a hide the internal details of the function from other software components

b remove some of the elements from the sequence

c select the formula that delivers the value of the function

d protect the function from damage by cosmic rays

2 The formula map reverse ["able", "was", "I"] delivers the value

a ["I", "saw", "elba"]

b ["elba", "saw", "I"]

c ["I", "was", "able"]

d ["able", "was", "I", "not"]

3 The formula map f xs delivers the value

a f x

b [f x | x <- xs]

c f xs

d [f xs]

4 Which of the following formulas is equivalent to the formula [g x y | y <- ys] ?

a (map . g x) ys

b (map g x) ys

c map (g x y) ys

d map (g x) ys

5 The following function delivers

HASKELL DEFINITION •     | xs == reverse xs = "yes"

HASKELL DEFINITION •     | otherwise = "no"

a "yes", unless xs is reversed

b "yes" if its argument is a palindrome, "no" if it’s not

c "no" if xs is not reversed

d "yes" if its argument is written backwards, "no" if it’s not

6 The following function

HASKELL DEFINITION •     | x < 0    = -1

HASKELL DEFINITION •     | x == 0 = 0

HASKELL DEFINITION •     | x > 0    = 1

a the value of its argument

b the negative of its argument

c a code indicating whether its argument is a number or not

d a code indicating whether its argument is positive, negative, or zero

7 Assuming the following definitions, which of the following functions puts in sequence of x’s in place of all occurrences of a given word in a given sequence of words?

HASKELL DEFINITION • rep n x = [ x | k <- [1 . . n]]

HASKELL DEFINITION •     | otherwise = word

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

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

1 c

f x
| x > 0 = 1
| otherwise = -1

2 b

3 b

map f xs = [f x | x <- xs]

4 d

map (g x) ys = map h ys = [ h y | y <- ys]

5 b

h xs

| (xs == reverse  xs)        = "yes"    -- 当一个序列如果等于它的反序时

| otherwise                     = "no"

6 d

7 a

rep n x = [ x | k <- [1 . . n]] 这个函数可以把x重复n次，这里的x并没有说是什么类型。

rep 3 '2'就是['2', '2', '2']，即"222"