【发布时间】:2014-11-20 18:44:13
【问题描述】:
我正在尝试减少元组列表,其中重复键的值像这样添加在一起:
[(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)]应该做什么? -
另外,你的主要问题是
[(k, v) : xs]匹配一个包含单个元素的列表,即(k, v) : xs,你应该匹配((k, v) : xs)。 -
@AdegokeA:该实现有效,但您确实会在某个地方需要
Map。您为什么要尝试更改该实施方式? -
您希望将什么确切传递给
reduce?一对钥匙?所有键的对? -
您是否要合并重复键的值?重复是否保证是连续的?你在哪里检查两个键是否匹配?