我在Haskell中有以下代碼,它在bookFromFile函數的第一行給出了一個錯誤。我究竟做錯了什麼?Haskell - 從文件中讀取數據並存儲到容器中
錯誤代碼如下。
import Data.List
import System.IO
type Book = (Int, String, String, String, String, String, String)
main = do
inputFile <- openFile "catalogo.txt" ReadMode
let b = (bookFromFile inputFile)
print "done"
bookFromFile :: Handle -> Book
bookFromFile inputFile = do
--Read&Store stuff from file
isbn <- fmap read (hGetLine inputFile) :: IO Int
title <- (hGetLine inputFile)
author <- (hGetLine inputFile)
genre <- (hGetLine inputFile)
date <- (hGetLine inputFile)
publisher <- (hGetLine inputFile)
summary <- (readSummary inputFile) --readSummary :: Handle -> IO String (works well)
putStr (summary ++ "\n")
--Construct and return a book
(isbn, title, author, genre, date, publisher, summary)
奇怪的是,(智力,字符串,字符串,字符串,字符串,字符串,整數)是不是連我都爲本書定義的類型。 錯誤消息:
* Couldn't match type `IO'
with `(,,,,,,) Int String String String String String'
Expected type: (Int, String, String, String, String, String, Int)
Actual type: IO Int
* In a stmt of a 'do' block:
isbn <- fmap read (hGetLine inputFile) :: IO Int
In the expression:
do { isbn <- fmap read (hGetLine inputFile) :: IO Int;
putStr ((show isbn) ++ "\n");
title <- (hGetLine inputFile);
putStr (title ++ "\n");
.... }
此代碼讀取像C轉化爲哈斯克爾,不地道的哈斯克爾.... Y上的小記錄類型你應該利用Haskell的懶惰,'readFile','lines'和一些純函數,這將真正展示選擇Haskell的理由。 – jamshidh