我試圖減少元組的列表,其中重複鍵的值加在一起是這樣的:哈斯克爾 - 減少列表 - MapReduce的
[(the, 1), (the, 1)] => [(the, 2)]
我嘗試這樣做:
reduce :: [(String, Integer)] -> [(String, Integer)]
reduce [] = []
reduce [(k, v) : xs] = (+) [(k, v)] : reduce xs
我得到這個錯誤:
Couldn't match expected type `(String, Integer)'
with actual type `[(String, Integer)] -> [(String, Integer)]'
我在做什麼錯?
編輯
這是一個完整的程序
toTuple :: [String] -> [(String, Integer)]
toTuple [] = []
toTuple (k:xs) = (k, 1) : toTuple xs
reduce :: [(String, Integer)] -> [(String, Integer)]
reduce [] = []
reduce [(k, v) : xs] = (+) [(k, v)] : reduce xs
main_ = do list <- getWords "test.txt"
print $ reduce $ toTuple list
-- Loads words from a text file into a list.
getWords :: FilePath -> IO [String]
getWords path = do contents <- readFile path
return ([Prelude.map toLower x | x <- words contents])
什麼是(+)[(k,v)]'應該在做什麼? – bheklilr 2014-11-20 19:01:01
另外,你的主要問題是'[(k,v):xs]'匹配一個包含單個元素的列表,即'(k,v):xs',你應該匹配'((k,v):xs )'而不是。 – bheklilr 2014-11-20 19:01:38
@bheklilr它應該添加一個K的v是一樣的。我試圖複製這個'map_list = M.toList $ M.fromListWith(+)[(x,1)| x < - list]' – 2014-11-20 19:02:28