《Two Dozen Short Lessons in Haskell》学习(十一)- Tuples

《Two Dozen Short Lessons in Haskell》(Copyright © 1995, 1996, 1997 by Rex Page,有人翻译为Haskell二十四学时教程,该书如果不用于赢利,可以任意发布,但需要保留他们的copyright)这本书是学习 Haskell的一套练习册,共有2本,一本是问题,一本是答案,分为24个章节。在这个站点有PDF文件。几年前刚开始学习Haskell的时候,感觉前几章还可以看下去,后面的内容越来越难以理解。现在对函数式编程有了一些了解后,再来看这些题,许多内容变得简单起来了。

初学Haskell之前一定要记住:

把你以前学习面向过程的常规的编程语言,如Pascal、C、Fortran等等统统忘在脑后,函数式编程完全是不一样的编程模型,用以前的术语和思维来理解函数式编程里的概念,只会让你困惑和迷茫,会严重地影响你的学习进度。

这个学习材料内容太多,想把整书全面翻译下来非常困难,只有通过练习题将一些知识点串起来,详细学习Haskell还是先看其它一些入门书籍吧,这本书配套着学学还是不错的。

第十一章 元组

元组必须有2个以上的元素

每个元素的类型可以不相同

元素之间用逗号分隔

元组里的元素放在一对括号中

元组的类型看上去也像一个元组,只不过它的元素是类型名。如(23, ‘x’)的类型是(Integer, Char)

利用元组,可以同时定义多个变量,如:(xSansLastDigit, d0) = x ‘divMod‘ 10

 

1 The type of the tuple ("X Windows System", 11, "GUI") is

a (String, Integer, Char)

b (String, Integer, String)

c (X Windows System, Eleven, GUI)

d (Integer, String, Bool)

 

2 After the following definition, the variables x and y are, respectively,

HASKELL DEFINITION • (x, y) = (24, "XXIV")

a both of type Integer

b both of type String

c an Integer and a String

d undefined — can’t define two variables at once

 

3 After the following definition, the variable x is

HASKELL DEFINITION • x = (True, True, "2")

a twice True

b a tuple with two components and a spare, if needed

c a tuple with three components

d undefined — can’t define a variable to have more than one value

 

4 After the following definition, the variable x is

HASKELL DEFINITION • x = 16 ‘divMod‘ 12

a 1 +4

b 16÷4

c 1 × 12 + 4

d (1, 4)

 

5 The formula divMod x 12 == x ‘divMod‘ 12 is

a (x ‘div‘ 12, x ‘mod‘ 12)

b (True, True)

c True if x is not zero

d True, no matter what Integer x is

 

6 In a definition of a tuple

a both components must be integers

b the tuple being defined and its definition must have the same number of components

c surplus components on either side of the equation are ignored

d all of the above

 

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

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

 

1 b

元组可以把不同的类型放在一起,它的类型就是放在括号中的几个类型的组合

 

2 c

用元组可以同时定义多个变量,这里的x就是整型,y是字符串类型

 

3 c

这是一个标准的元组定义

 

4 d

divMod是个函数,通常的写法把参数跟在函数名的后面,而`divMod`就可以把函数名放在二个参数中间。

divMod返回一个元组,元组的第一个元素是商(取整后),第二个元素是余数。

 

 

5 d

返回两个元组相等时,返回值是一个布尔值True,而不是(True, True)

 

6 b

(2,3)与(2,3,4)是两种不同的元组,前者的类型是(Integer, Integer),后者的类型是(Integer, Integer, Integer),这两个元组是不能相互比较的。

posted @ 2012-12-13 20:55  申龙斌的程序人生  阅读(1327)  评论(0编辑  收藏  举报