20
votes
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?

2
your function assumes as can be compared with ==, you have to put this info in the type signature.Karoly Horvath
Because (==) is a member of the Eq class. So you can use it only on types that are instances of Eq.Daniel Fischer
Real world haskell chap 3? Me too!Jason

2 Answers

34
votes

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.

0
votes

hammar explanation is correct.

Another simple example:

nosPrimeiros :: a -> [(a,b)] -> Bool
nosPrimeiros e [] = False
nosPrimeiros e ((x,y):rl) = if (e==x)   then True
                                        else nosPrimeiros e rl

The (e==x) will fail for this function signature. You need to replace:

nosPrimeiros :: a -> [(a,b)] -> Bool

adding an Eq instance for a

nosPrimeiros :: Eq => a -> [(a,b)] -> Bool

This instantiation is saying that now, a has a type that can be comparable with and (e==x) will not fail.