[Haskell-beginners] Meaning of (Eq a)
Hein Hundal
hundalhh at yahoo.com
Sun Sep 5 06:20:46 EDT 2010
> Date: Sun, 5 Sep 2010 14:28:09 +0530
> From: Rohit Garg <rpg.314 at gmail.com>
>
> 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
More information about the Beginners
mailing list