I’m really at a loss to explain why this is a type error:
foo :: (Eq a) => a -> a
foo _ = 2
Can anyone explain?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because the type of
should be String, according to your signature, but is not (2 is not a String). In your code foo is generic, so it should return an instance of exactly the same type as the argument.
The power of haskell type system gives us additional information – all you can do with the argument inside foo is to check for its equality with something else, but as I can come up with any new type (lets call it Baz) and use foo on it – you can’t possibly have any other instances of Baz, so the only way to return an instance of Baz is to return the exact same instance as the argument.
If you rewrote foo like so:
it would have a signature of
foo :: a -> Bool, this is basically what you tried to do, but things get more complicated with numbers.In general your function has a signature
which means that it returns a Num instance for any given argument. (This is because 2 can have many different types in haskell, depending on what you need it can be an Int or a Real or other.)
You should play around with types in ghci, for example:
will give you the infered type signature for foo.
gives you
(Num t) => twhich means that 2 can be an instance of any type which implements Num.