《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還是先看其它一些入門書籍吧,這本書配套著學學還是不錯的。
第18章?Interactive Keyboard Input and Screen Output
IO類型在初學Haskell的時候是一個很難理解的概念,平常的編程語言中已經習慣了輸入、輸出語句,但在函數式編程中一切皆函數,一個確定的函數會得到確定的計算結果,而與操作系統交互時函數式編程就不太方便了,這時Haskell引出了一個IO類型。
一個重要的do表達式:
這一章還介紹了一個字符串連接的函數,可以把字符串末尾加上換行符,再連接起來
unlines :: [String] -> String
unlines = concat . map (++ "\n")
例如:
unlines ["line1", "line2", "line3"]?=?"line1\nline2\nline3\n"
?
1 Values of IO type
a are in the equality class Eq
b specify requests for operating system services
c represent tuples in a unique way
d describe Jovian satellites?
?
2 Which of the following intrinsic functions in Haskell causes output to appear on the screen?
a concat :: [[any]] -> [any]
b putStr :: String -> IO ()
c printString :: Message –> Screen
d getLine :: IO String?
?
3 What will be the effect of the command main, given the following script?
HASKELL DEFINITION ?main =
HASKELL DEFINITION ??? do putStr "Good "
HASKELL DEFINITION ???????? putStr "Vibrations\n"
HASKELL DEFINITION ???????? putStr " by the Beach Boys\n"
a one line displayed on screen
b two lines displayed on screen
c three lines displayed on screen
d audio effects through the speaker?
?
4 What will be the effect of the command main, given the following script?
HASKELL DEFINITION ? main =
HASKELL DEFINITION ??? do putStr "Please enter your first and last name (e.g., John Doe): "
HASKELL DEFINITION ???????? firstLast <- getLine
HASKELL DEFINITION ???????? putStr (reverse firstLast)
a display of name entered, but with the last name first
b display of last name only, first name ignored
c display of last name only, spelled backwards
d display of name spelled backwards (書中在這里有印刷錯誤)?
?
5 How should the last input/output directive in the preceding question be changed to display the first name only?
什么時候只輸出名字?
a putStr(take 1 firstLast)
b putStr(drop 1 firstLast)
c putStr(takeWhile (/= ’ ’) firstLast)
d putStr(dropWhile (/= ’ ’) firstLast)?
?
=========================================================
答
案
在
下
面
=========================================================
1 b?
?
2 b
putStr函數返回的類型是IO (),表示要與操作系統有交互動作,這個()表示不返回任何數據。
?
3 b
結果應該是:
Good?Vibrations
?by the Beach Boys
?
4 d
如果輸入是John Doe
則屏幕輸出:eoD nhoJ
?
5 c
如果輸入是John Doe
選項a:take 1 firstLast,會取出第一個字符,“J"?
選項b:drop 1 firstLast,會除掉第一個字符, "ohn Doe"
選項c:takeWhile (/=' ') firstLast,會得到空格前的字符串,"John",是正確答案。
選項d:dropWhile (/=' ') firstLast,會除掉第一個空格前的所有字符," Doe",注意Doe前面還有一個空格?