[Haskell-beginners] typeclass error

Quentin Moser quentin.moser at unifr.ch
Tue Apr 21 10:02:55 EDT 2009


On Tue, 21 Apr 2009 09:27:57 -0400
Amitava Shee <amitava.shee at gmail.com> wrote:

> I have the following code
> 
> -- foo.hs
> module Foo where
> 
> class Foo a where
>     bar :: a -> a
> 
> instance Foo Int where
>     bar i = i + 10
> 
> ------------------
> 
> It fails to compile withe following error
> *Foo> bar 10
> 
> <interactive>:1:4:
>     Ambiguous type variable `t' in the constraints:
>       `Num t' arising from the literal `10' at <interactive>:1:4-5
>       `Foo t' arising from a use of `bar' at <interactive>:1:0-5
>     Probable fix: add a type signature that fixes these type
> variable(s) *Foo>
> 

When you type an expression into GHCi, it needs to be able to assign
it a monomorphic type (a type without variables) in order to know
which "show" to use on it to print it. From the types of bar (Foo a =>
a -> a) and 10 (Num a => a), GHCi can only deduce that bar 10 should
have type ((Foo a, Num a) => a). It's also not smart enough to notice that
there's only one type that's an instance of both Foo and Bar, and use
it.

Your declarations are perfectly fine, but there's not enough information
at the call site of bar to pin it down to a particular type. It can be
solved simply by adding a type signature there (bar 10 :: Int).



Note also that, since numeric code is common and uses a lot of type
classes, Haskell has ad-hoc defaulting rules for it: When there's an
ambiguity on the type of a variable and at least one of its class
constraints is numeric (e.g. Num or Integral), the compiler will try to
use a default type. Unfortunately the default Num type is Integer
which isn't an instance of Foo, so the defaulting rules don't apply in
your case.


More information about the Beginners mailing list