Homework: Comparing Intermediate Expressions with == in Haskell

I wrote the code below to check if the list is a palindrome or not. To my surprise, it does not compile with the error "There is no instance for (Eq a) resulting from the use of == ...". My guess is that the compiler does not know that leftHalfand rightHalfare lists.

    isPalindrome :: [a] -> Bool
    isPalindrome [] = False
    isPalindrome xs = if (leftHalf == reverse rightHalf)
              then True
              else False
     where leftHalf = take center xs
           rightHalf = drop center xs
           center = if  even (length xs)
                       then (length xs) `div` 2
                   else ((length xs) - 1) `div` 2 

1) How to tell the compiler leftHalfand rightHalfare lists?
2) How can I use pattern matching or other haskell functions to solve this problem?

EDIT: Thanks to everyone for your input. Special mention to Matt Fenwick for documentation links and Duri for an elegant tip. I will write the final decisions below just in case

     isPalindrome' :: (Eq a) => [a] -> Bool
     isPalindrome' [] = False
     isPalindrome' xs = if p then True else False
                   where p = leftHalf == rightHalf
                         leftHalf = take c xs
                         rightHalf = take c (reverse xs)
                         c = div l 2
                         l = length xs

isPalindrome' ,

      isPalindrome'' :: (Eq a) => [a] -> Bool
      isPalindrome'' [] = False
      isPalindrome'' xs = if (reverse xs) == xs then True else False
+3
3

Eq:

ghci> :i (==)
class Eq a where
  (==) :: a -> a -> Bool
  ...
    -- Defined in GHC.Classes
infix 4 ==

isPalindrome.

,

if (leftHalf == reverse rightHalf)
              then True
              else False

.

+2

, , , . [a] , a Eq.

, :

x = if c then True else False

x = c
+4

You must change your type to:

isPalindrome :: Eq a => [a] -> Bool

And it’s really an outsider to find a center, just write xs == reverse xs- when you calculate length xs, you go through the entire list and there is no economy.

+1
source

All Articles