[Haskell-cafe] type inference futility

Peter Berry pwberry at gmail.com
Mon Apr 16 11:19:12 EDT 2007

On 16/04/07, Paul Wankadia <junyer at gmail.com> wrote:
> Is it impossible for the compiler to infer the type from the methods called?

Your code:

> main :: IO ()
> main = do
>         x <- new

>From the use of 'new', the compiler can infer that the type of x is an
instance of MehBase, and...

>         shift x

from the use of 'shift', that it is an instance of HasShift.

>         return ()

So we have x :: (MehBase a, HasShift a) => a. There isn't enough
information provided to pin down 'a' any more precisely, so GHC can't
figure out which 'new' or 'shift' you mean (remember that type classes
provide overloading), and gives up.

There is one special case where the compiler does infer a specific
type despite not having enough information to do so, and that is where
the class(es) is/are numeric. For example (Floating a) => a might
default to Float or Double. This is one case where the compiler
decides it can make 'reasonable' assumptions as to what you actually
wanted. It's also why ambiguous types seem to work in the interpreter,
if you've only ever looked at numeric ones. In the case of the code
you posted, GHC isn't smart enough to realise that there's only one
type in scope that satisfies the constraints.

Here's the relevant part of the report:

Felipe's suggestion is probably the best way to fix it, i.e. tell the
compiler exactly which type you want. The report seems to suggest you
can give the compiler a list of defaults in the module declaration but
I don't know if that would be sensible.

Peter Berry <pwberry at gmail.com>
Please avoid sending me Word or PowerPoint attachments.
See http://www.gnu.org/philosophy/no-word-attachments.html

More information about the Haskell-Cafe mailing list