我试图编写一个检查列表是否为回文并返回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 ``=='
的来源。它试图推断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
在我的建议中,=>
之前的内容称为上下文,可以在其中为类型添加约束。这里的建议是告诉您完全按照我在上面所说的做(尽管以更详细的方式)。