我不明白为什么这些函数有错误:
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
Run Code Online (Sandbox Code Playgroud)
错误信息:
Run Code Online (Sandbox Code Playgroud)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
有谁可以解释,我错了什么?
谢谢!
foldr :: (a -> b -> b) -> b -> [a] -> b可以在Hoogle上找到该表单的功能a -> b -> b,但您的test功能看起来很像a -> a -> b.
正如Carsten所提到的b,你的函数甚至与b累加器不匹配,并且在使用时可以从GHCi中检索信息:t foldr(这可以用于任何函数).您尝试做的事情的替代方案可能是(如果我做对了,你试着计算双打的数量):
countEqualPairs [] = 0
countEqualPairs (s:ss) = if (s `elem` ss) then 1 + x else x
where x = countEqualPairs ss
Run Code Online (Sandbox Code Playgroud)