天天看點

《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),這兩個元組是不能互相比較的。

http://www.cnblogs.com/speeding/ 

繼續閱讀