Haskell:由于使用'=='而没有出现(方程a)的实例 [英] Haskell: No instance for (Eq a) arising from a use of `=='
本文介绍了Haskell:由于使用'=='而没有出现(方程a)的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
isPalindrome :: [a] - > Bool
isPalindrome xs =
[] - >的情况xs True
[x] - >真
a - > (last a)==(head a)&& (isPalindrome(drop 1(take(length a - 1)a)))
main = do
print(show(isPalindromeblaho))
$ c
$ b
$ b
(方程a)由于使用'=='而引起的
在'(&& amp;)'的第一个参数中,即'(last a)==(head a)'
在表达式中:
(last a)==(head a)
&& (isPalindrome(drop 1(take(length a - 1)a)))
在另一种情况下:
a - > (last a)==(head a)
&& (isPalindrome(drop 1(take(length a - 1)a)))
为什么这个错误发生?
解决方案 您正在比较使用 a
==
。这意味着 a
不能是任何类型 - 它必须是 Eq
的一个实例,因为类型 ==
是(==):: Eq a => a - > a - > Bool
。
你可以通过在<$ c上添加一个 Eq
约束来解决这个问题。
isPalindrome :: Eq a =>> $ c> a
; [a] - > Bool
顺便说一下,使用反向
。
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"))
results in
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)))
Why is this error occurring?
解决方案 You're comparing two items of type a
using ==
. That means a
can't just be any type - it has to be an instance of Eq
, as the type of ==
is (==) :: Eq a => a -> a -> Bool
.
You can fix this by adding an Eq
constraint on a
to the type signature of your function:
isPalindrome :: Eq a => [a] -> Bool
By the way, there is a much simpler way to implement this function using reverse
.
这篇关于Haskell:由于使用'=='而没有出现(方程a)的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文