我试图减少元组列表,其中重复键的值加在一起如下:
[(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])
答案 0 :(得分:1)
您正在进行错误的模式匹配。模式匹配应该是这样的:
((k,v):xs)
(k,v)
表示列表的头部,xs
表示列表的尾部。同样,这也存在问题:
(+) [(k, v)] : reduce xs
+
的类型是:
λ> :t (+)
(+) :: Num a => a -> a -> a
你不能简单地(+) [(k, v)] : reduce xs
做任何不合理的事情。您必须检查字符串的内容,然后添加元组的第二部分。