Beta Reduction, undefined vs Type Classes
Keith.Wansbrough at cl.cam.ac.uk
Mon Nov 10 11:44:27 EST 2003
> > class Thing t where
> > thing :: t
> Can someone please explain why
> > fst (1,thing)
> ...gets an 'ambiguous type variable' error, but
> > fst (1,undefined)
> ...doesn't? And is there anything I can change to make the former work
> as well? Even modifying fst doesn't work:
This kind of thing is a bit of a "trap for young players". You'll get errors when entering things into the interactive toplevel (hugs/ghci), but if you put it in a program you will almost certainly not get the errors, because more information will be available to the compiler from a full program than from a toy example.
The problem is that the member function "thing" doesn't take anything of type t by which the compiler might infer which instance it is. You can see this even more easily by typing
To fix it, give it a type annotation:
fst (1,thing::Thing Int)
The reason you don't get the error for fst (1,undefined) is because undefined has the perfectly good type (forall a. a), and so (1,undefined) has type (forall a. (Integer,a)) and fst (1,undefined) has type Integer. Polymorphism (like the type of undefined) is much better behaved than overloading (like the types of thing).
It's actually more complicated than this, though - 1 actually has type Num a => a, but Haskell has a built-in "defaulting" rule which says that anything of this type should default to Integer or Double, in that order. So you don't get ambiguity errors for simple numbers. This makes life simpler when using Haskell as a calculator.
Keith Wansbrough <kw217 at cl.cam.ac.uk>
University of Cambridge Computer Laboratory.
More information about the Haskell-Cafe