Haskell:使用foldr在函数中输入不匹配

时间:2015-06-12 09:18:45

标签: haskell

我不明白为什么这些功能出错:

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

有谁可以解释,我错了什么?

谢谢!

2 个答案:

答案 0 :(得分:5)

可以在Hoogle上找到

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