繁体   English   中英

Haskell:使用`=='时没有(Eq a)的实例

[英]Haskell: No instance for (Eq a) arising from a use of `=='

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)))

为什么会出现此错误?

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

您可以通过添加一个解决这个Eq对约束a给你的函数的类型签名:

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

顺便说一下,有一种更简单的方法可以使用reverse来实现这个功能。

哈马尔解释是正确的。

另一个简单例子:

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)不会失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM