我想獲得一個函數工作,使用foldl 來通過元組列表並從中創建一個字符串。 我正試圖創建一個類似的函數,它已經可以使用遞歸。Haskell使用foldl像遞歸
這裏是我想要編譯代碼:
citeBook :: (String, String, Integer) -> String
citeBook (name, titl, date) = (titl ++ " (" ++ name ++ ", " ++ show date ++ ")\n")
--Recursion function
-- function must be called with putStr in order for newlines to work
bibliography_rec :: [(String, String, Integer)] -> String
bibliography_rec [] = ""
bibliography_rec xs = (citeBook(head xs) ++ bibliography_rec (tail xs))
--foldl function
bibliography_fold :: [(String, String, Integer)] -> String
bibliography_fold [] = ""
bibliography_fold (x:xs) = foldl (++) citeBook(x) xs --ERROR HERE
因此,在所提供的代碼的最後一行,我想有與foldl 使用(++)作爲運營商爲了組合列表中的字符串。 我使用citeBook(x)作爲我的基本情況,因爲x將是從列表中取出的第一個元組 。請注意,citeBook(x)返回一個字符串。然後繼續使用列表xs摺疊 。
這是我收到的錯誤。我想我的參數類型與foldl不 與預期一致,但一切似乎還好我..
hw1.hs:28:34:
Couldn't match type `[a0]'
with `(String, String, Integer) -> String'
Expected type: ((String, String, Integer) -> String)
-> [a0] -> (String, String, Integer) -> String
Actual type: [a0] -> [a0] -> [a0]
In the first argument of `foldl', namely `(++)'
In the expression: foldl (++) citeBook (x) xs
In an equation for `bibliography_fold':
bibliography_fold (x : xs) = foldl (++) citeBook (x) xs
hw1.hs:28:48:
Couldn't match expected type `[[a0]]'
with actual type `(String, String, Integer)'
In the third argument of `foldl', namely `(x)'
In the expression: foldl (++) citeBook (x) xs
In an equation for `bibliography_fold':
bibliography_fold (x : xs) = foldl (++) citeBook (x) xs
hw1.hs:28:51:
Couldn't match expected type `(String, String, Integer)'
with actual type `[(String, String, Integer)]'
In the fourth argument of `foldl', namely `xs'
In the expression: foldl (++) citeBook (x) xs
In an equation for `bibliography_fold':
bibliography_fold (x : xs) = foldl (++) citeBook (x) xs
我明白任何和所有的反饋。謝謝!
是不是'bibliography_rec'只是'concatMap citeBook'? – bheklilr
是的,發佈作爲答案。 – amnn
bheklilr,我只是試過了,它確實工作,但我明確地試圖創建一個遞歸函數。我的問題是我試圖打印出一個列表,就像bibliography_rec一樣,但是使用foldl而不是遞歸 –