
Date: Sun, 5 Sep 2010 14:28:09 +0530 From: Rohit Garg
RWH: chapter 3 - in question 5, you have to write a function which determines if a list is a palindrome. Here is my solution
isPalindrome :: (Eq a) => [a] -> Bool isPalindrome [] = False isPalindrome x = compareLists x (reverse x) where compareLists [x] [y] = x == y compareLists (x:xs) (y:ys) = if x == y then compareLists xs ys else False
Although it works, my question is why ghci refuses to run it without the "(Eq a) => " being added to the type signature of the function. Presumably, it is to let ghc know that you can perform equality tests on a. If so, then why does the sumList function below work without any type signature of any kind? I haven't told ghc that the input list elements can be added together.
sumList [] = 0 sumList (x:xs) = x + sumList xs
When I compile isPalindrome with ghc 6.12.1, I do not get any errors even if I drop the type signature. If I drop the type signature and use ghci to get the type signature (":t isPalindrome"), then I get *Main> :t isPalindrome isPalindrome :: (Eq t) => [t] -> Bool So, it seems that ghc 6.12.1 correctly infers the types. Cheers, Hein PS: Haskell does equality of lists, so you can also use the definition isPalindrome v = v == reverse v