Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: No instance for (Eq a) arising from a use of `=='

Tags:

haskell

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?

like image 985
Muhd Avatar asked Apr 22 '13 18:04

Muhd


1 Answers

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.

like image 82
hammar Avatar answered Nov 16 '22 02:11

hammar