# 《Two Dozen Short Lessons in Haskell》学习（四）

## 第四章 Computations on Sequences — List Comprehensions

1 The following function delivers

HASKELL DEFINITION • f str = [ c | c <- str, c == ’x’ ]

a all the c’s from its argument

b an empty string unless its argument has x’s in it

c a string like its argument, but with x’s in place of c’s

d nothing — it contains a type mismatch, so it has no meaning in Haskell

2 The following command delivers

HASKELL DEFINITION • g str = [ c | c <- str, c == "x" ]

HASKELL COMMAND • g "xerox copy"

a "c"

b "xx"

c "xerox xopy"

d error — g expects its argument to be a sequence of strings, not a sequence of characters

3 The following function delivers a string like its argument, but …

HASKELL DEFINITION • h str = [ c | c <- reverse str, c < ’n’ ]

a written backwards if it starts with a letter in the first half of the alphabet

b written backwards and without n’s

c written backwards and without letters in the first half of the alphabet

d written backwards and without letters in the last half of the alphabet

4 Which of the following equations defines a function that delivers a string like its second argument, but with no letters preceding, alphabetically, the letter specified by its first argument?

A HASKELL DEFINITION • s x str = [ c | c <- str, c < x ]

B HASKELL DEFINITION • s x str = [ c | c <- str, c >= x ]

C HASKELL DEFINITION • s abc str = [ c | c <- str, c == "abc"]

D HASKELL DEFINITION • s abc str = [ c | c <- str, c /= "abc"]

5 In the following definition, the parameter str

HASKELL DEFINITION • f str = [ c | c <- str, c == ’x’ ]

a represents the letter x

b represents the letter c

c stands for a sequence of x’s

d stands for a string containing a sequence of characters

1 b

f str = [ c | c <- str, c == ’x’ ]

list Comprehensions应该是haskell里强大的特性了，[ 左边 | 右边 ]，在竖线的左边是一个表达式（感觉叫表达式不太准确），右侧表示参数的取值范围和条件，右侧可以是生成器generator，像v <- expr这样，也可以是一个布尔过滤条件guard，像c<x这样。

2 d

'x’与"x”是两种不同类型的值，前面是Char，后面的是[Char]或称为String

3 d

'n’是26个字母中的第14个字母，c < ’n’ 就是指字母表的前半部分，也就是没有后半部分字母。

4 b

s x str = [ c | c <- str, c >= x ]这个函数定义中有2个参数，意思就是把str字符串中的所有大于或等于x的字母全筛选出来

5 d

f str = [ c | c <- str, c == ’x’ ]

[ c | c <- str, c == ’x’ ]是一个列表，而列表中的元素是字符，所以str的类型就是[Char]，也就是String

posted @ 2012-11-11 16:39  申龙斌的程序人生  阅读(503)  评论(0编辑  收藏  举报