[Haskell-beginners] Meaning of (Eq a)

Markus Läll markus.l2ll at gmail.com
Sun Sep 5 07:12:24 EDT 2010

I have not tested, but I suspect, that if you don't provide a type
signature for either isPalindrome or sumList, it will get inferred
correctly. The problem is that if you *do* provide a typesignature for
either of them, you *have* to give it a properly constrained

I think for sumList a signature of [a] -> a does not work, because you
use the adding function, which has type (Num a) -> a -> a -> a. So
when providing a signature for sumList you have to add the Num a
constraint too. The same goes for isPlindrome, where Eq a is
neccessary because of the type of ==.

Like, for isPalindrome the signature [a] -> Bool is not correct,
because it says any 'a' will work (because it is not constrained), but
any 'a' wont work -- it has to be an equitable 'a', thus the (Eq a)

The point is, that when providing a signature, it has to be
sufficently (or more) constrained -- GHC won't patch it wor you, but
if the signature is missing it will (try to) infer it.


On Sun, Sep 5, 2010 at 1:20 PM, Hein Hundal <hundalhh at yahoo.com> wrote:
>> 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
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners

More information about the Beginners mailing list