[Haskell-beginners] Meaning of (Eq a)
Lakshmi Narasimhan
lakshminaras2002 at gmail.com
Sun Sep 5 05:19:50 EDT 2010
On 09/05/2010 02:28 PM, Rohit Garg wrote:
> Hi,
>
> 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 equlity 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
>
>
> Thanks,
Hi Rohit,
You are correct about the assumption. Giving (Eq a) is constraining the
set of types that can be used with to the palindrome function. The
elements of the type a can be tested for equality.
The compiler can perform type inference. It will find out the type
signature if you do not provide one. Assume that you did not provide the
type signature for the isPalindrome function, here is what I get when I
loaded this code into ghci.
*Main> :t isPalindrome
isPalindrome :: (Eq t) => [t] -> Bool
For the sumList function, since you did not provide the type
information, the compiler will infer the type for the argument and
result of the function. However, as you point out correctly, not all
types can be added. Hence constraint (Num t) will be added to the type
signature. This means that the elements of the type "t" can be added.
If not, then that type cannot be used and a compiler error will result.
sumList :: (Num t) => [t] -> t
Hope that helps
-Lakshmi Narasimhan
More information about the Beginners
mailing list