我不明白为什么这些功能出错:
countEqualPairs:: Eq a => [a] -> Int
countEqualPairs (s:ss) = foldr test s ss
test :: Eq a => a -> a -> Int
test s c = if (c == s) then 1 else 0
错误讯息:
Could not deduce (a ~ Int) from the context (Eq a) bound by the type signature for countEqualPairs :: Eq a => [a] -> Int at Blatt06.hs:30:20-37 `a' is a rigid type variable bound by the type signature for countEqualPairs :: Eq a => [a] -> Int at Blatt06.hs:30:20 Relevant bindings include ss :: [a] (bound at Blatt06.hs:31:20) s :: a (bound at Blatt06.hs:31:18) countEqualPairs :: [a] -> Int (bound at Blatt06.hs:31:1) In the second argument of `foldr', namely `s' In the expression: foldr test s ss
有谁可以解释,我错了什么?
谢谢!
答案 0 :(得分:5)
foldr :: (a -> b -> b) -> b -> [a] -> b
期望a -> b -> b
形式的函数,但您的test
函数看起来像a -> a -> b
。
提到Carsten时,您的函数的b
甚至与累加器中的b
不匹配,并且在使用:t foldr
时可以从GHCi检索信息(这可以为任何功能完成)。您尝试做的事情的替代方案可能是(如果我做对了,你试着计算双打数量):
countEqualPairs [] = 0
countEqualPairs (s:ss) = if (s `elem` ss) then 1 + x else x
where x = countEqualPairs ss
答案 1 :(得分:0)
非常感谢您提供有用的评论和答案。我这样解决了:
countEqualPairs :: Eq a => [a] -> Int countEqualPairs ss = sum (zipWith test (init ss) (tail ss)) test :: Eq a => a -> a -> Int test c1 c2 = if (c1 == c2) then 1 else 0