20
isPalindrome :: [a] -> Bool
isPalindrome xs = case xs of 
                        [] -> True 
                        [x] -> True
                        a -> (last a) == (head a) && (isPalindrome (drop 1 (take (length a - 1) a)))

main = do
    print (show (isPalindrome "blaho"))

结果是

No instance for (Eq a)
  arising from a use of `=='
In the first argument of `(&&)', namely `(last a) == (head a)'
In the expression:
  (last a) == (head a)
  && (isPalindrome (drop 1 (take (length a - 1) a)))
In a case alternative:
    a -> (last a) == (head a)
         && (isPalindrome (drop 1 (take (length a - 1) a)))

为什么会出现这个错误?

4

2 回答 2

35

您正在使用 比较两个类型的a项目==。这意味着a不能只是任何类型 - 它必须是 的实例Eq,就像 的类型==一样(==) :: Eq a => a -> a -> Bool

您可以通过在函数的类型签名Eq上添加约束来解决此问题:a

isPalindrome :: Eq a => [a] -> Bool

顺便说一句,有一种更简单的方法可以使用reverse.

于 2013-04-22T19:01:00.947 回答
0

哈马尔的解释是正确的。

另一个简单的例子:

nosPrimeiros :: a -> [(a,b)] -> Bool
nosPrimeiros e [] = False
nosPrimeiros e ((x,y):rl) = if (e==x)   then True
                                        else nosPrimeiros e rl

(e==x) 对于此函数签名将失败。您需要更换:

nosPrimeiros :: a -> [(a,b)] -> Bool

为 a 添加一个 Eq 实例

nosPrimeiros :: Eq => a -> [(a,b)] -> Bool

这个实例化是说现在,a有一个可以和 (e==x)比较的类型,不会失败。

于 2014-10-12T15:35:14.493 回答