我试图编写一个程序来检查列表是否是回文并返回布尔。
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.
由于我不是非常有经验,所以我不理解错误消息中的内容。因此,我看不出代码中的错误所在。感谢您的帮助。
答案 0 :(得分:5)
问题是您需要约束多态类型unary_op
。目前,编译器没有有关类型的信息,因此它甚至不知道是否为a
定义了(==)
(这就是a
的来源。它试图为No instance for (Eq a) arising from a use of ``=='
推断一个Eq
的实例,但是无法。您需要帮助)。
您应该输入:
a
现在您要告诉它,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
之前的内容称为上下文,您可以在其中为类型添加约束。这里的建议是告诉您完全按照我在上面所说的做(尽管以更详细的方式)。
答案 1 :(得分:0)
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) )