# 《Two Dozen Short Lessons in Haskell》学习（十四）- Truncating Sequences and Lazy Evaluation

## 第十四章 截断序列和惰性求值

1 What is the value of w?

HASKELL DEFINITION • u, v, w :: String

HASKELL DEFINITION • u = "Four vier cuatro"

HASKELL DEFINITION • v = drop 5 u

HASKELL DEFINITION • w = drop 5 v

a "Four "

b "vier "

c "cuatro"

d "cinco"

2 What string does the following command deliver?

HASKELL COMMAND • takeWhile (/= blank) "Four score and seven"

a "score and seven"

b " score and seven"

c "Four "

d "Four"

3 What string does the following command deliver?

HASKELL COMMAND • dropWhile (/= blank) "Four score and seven"

a "score and seven"

b " score and seven"

c "Four "

d "Four"

4 What value does the following command deliver?

HASKELL DEFINITION • dozen = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]

HASKELL COMMAND • [ take 2 xs | xs <- iterate (drop 2) dozen ]

a [1, 2, 3, 4, 5, 6]

b [ [1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12], [ ], [ ], [ ], [ ], [ ], … ]

c [2, 4, 6, 8, 10, 12]

d [ [1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12] ]

5 Which of the following formulas delivers the product of the numbers in the sequence xs?

a dropWhile (/= 0) (iterate (*) xs)

b takeWhile (/= 0) (iterate (*) xs)

c foldr (*) 0 xs

d foldr (*) 1 xs

6 Given the following definition, which of the formulas delivers the number 3?

HASKELL DEFINITION • k x y = x

HASKELL DEFINITION • first, second, third :: Integer

HASKELL DEFINITION • first = k (4-1) 0

HASKELL DEFINITION • second = k (1+2) "three"

HASKELL DEFINITION • third = k 3 (1 ‘div‘ 0)

a first

b second

c third

d all of the above

7 Consider the following function.

HASKELL DEFINITION • f :: String -> [String]

HASKELL DEFINITION • f w = [take 2 w, drop 2 w]

What does the formula iterate f "cs1323" deliver?

a [ "cs", "1323", [ ], [ ], …

b [ "cs", "13", "23", [ ], [ ], …

c [ ["cs"], ["1323"], [ ], [ ], …

d error … type mismatch

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

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

1 c

drop n list函数的功能就是把一个列表list中的前n个元素扔掉。

drop 5 u为"vier cuatro"

drop 5 v就是"cuatro”

2 d

takeWhile cond list函数可以按面向过程的函数来理解。

haskell总是在最后一刻才进行求值计算，比如takeWhile (>3) [4, 5, 2, (3^1000) ]

(== 0) x                x == 0

(< 0) x                 x < 0

(‘div‘ 10) x            x ‘div‘ 10

(c+) x                   c + x

(1-) x                   1 - x

3 b

4 b

iterate (drop 2) dozen是一个迭代方法，把函数(drop 2)先应用于列表dozen上，然后再不断地迭代应用于后续生成的结果上。

......

[ [1,2,3,4,5,6,7,8,9,10,11,12],

[3,4,5,6,7,8,9,10,11,12],

[5,6,7,8,9,10,11,12],

[7,8,9,10,11,12],

[9,10,11,12],

[11,12],

[], [], ... ]

[[1,2], [3,4], [5,6], [7,8], [9,10], [11,12], [], [], ... ]

5 d

6 d

7 d

iterate函数要求输入参数和输出函数是相同类型的，这样才能无限迭代下去。

posted @ 2013-01-29 22:49  申龙斌的程序人生  阅读(1065)  评论(0编辑  收藏  举报