Haskell 中的 isPalindrome 函数给出错误

isPalindrome function in Haskell gives an error

我正在尝试编写一个程序来检查列表是否为回文和 returns Bool。

isPalindrome :: [a] -> Bool
isPalindrome [] = True
isPalindrome [x] = True
isPalindrome xs | (head xs) == (last xs) = isPalindrome (init(tail xs))
                | otherwise = False

我收到了这样的错误消息:

problem6.hs:4:19: error:
    * No instance for (Eq a) arising from a use of `=='
      Possible fix:
        add (Eq a) to the context of
          the type signature for:
            isPalindrome :: forall a. [a] -> Bool
    * In the expression: (head xs) == (last xs)
      In a stmt of a pattern guard for
                     an equation for `isPalindrome':
        (head xs) == (last xs)
      In an equation for `isPalindrome':
          isPalindrome xs
            | (head xs) == (last xs) = isPalindrome (init (tail xs))
            | otherwise = False
  |
4 | isPalindrome xs | (head xs) == (last xs) = isPalindrome (init(tail xs))
  |                   ^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.

因为我不是很有经验,所以从报错信息中看不懂。所以我看不出我的代码哪里出了问题。感谢您的帮助。

问题是您需要限制多态类型 a。现在,编译器没有关于类型的信息,所以它甚至不知道 (==) 是否为 a 定义(这是 No instance for (Eq a) arising from a use of ``==' 的来源。它试图为 a 推断出 Eq 的一个实例,但它不能。你需要一起帮助它)。

你应该打字:

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

现在你告诉它 isPalindrome 只能给出属于 Eq.

实例的事物列表

它指出这篇文章是因为您正在尝试比较两个 a 的相等性:

(head xs) == (last xs)

关于错误信息的一点点:

 Possible fix:
    add (Eq a) to the context of
      the type signature for:
        isPalindrome :: forall a. [a] -> Bool

在我的建议中 => 之前的内容称为上下文,您可以在其中为您的类型添加约束。这里的建议是告诉你完全按照我上面说的去做(尽管以更冗长的方式)。

import Data.List

isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome [] = True
isPalindrome [x] = True
isPalindrome xs    
                | (head xs /= head (reverse xs)) = False
                | otherwise = isPalindrome ( tail (init xs) )