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

Muh*_*uhd 17 haskell

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"))
Run Code Online (Sandbox Code Playgroud)

结果是

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)))
Run Code Online (Sandbox Code Playgroud)

为什么会出现此错误?

ham*_*mar 31

你比较型的两个项目a使用==.这意味着a不能仅仅是任何类型-它必须是一个实例Eq,作为类型==(==) :: Eq a => a -> a -> Bool.

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

isPalindrome :: Eq a => [a] -> Bool
Run Code Online (Sandbox Code Playgroud)

顺便说一下,有一种更简单的方法来实现这个功能reverse.

  • 根据lambdabot,`isPalindrome = reverse >> =(==)`:D (8认同)