[Haskell-beginners] question on types

Brent Yorgey byorgey at seas.upenn.edu
Fri Jul 29 17:24:45 CEST 2011


On Fri, Jul 29, 2011 at 11:02:26AM -0400, Jake Penton wrote:
> 
> On 2011-07-29, at 10:02 AM, Daniel Seidel wrote:
> 
> > On Fri, 2011-07-29 at 09:49 -0400, Jake Penton wrote:
> >> For example, this does not compile: 
> >> 
> >> f :: Fractional a => a 
> >> f = 3.14 
> > 
> > I can load this to ghci and also compile
> > 
> 
> Yeah, sorry - so can I. I must have screwed up earlier. Fat fingers, bleary eyes....
> 
> But, getting back to my point (or possibly making an unrelated one for all I know), how about this, which I *hope* I am right in saying does NOT compile, even though Bool is an instance of Ord:
> 
> g :: Ord a => a
> g = True
> 
> It still seems to me that the mere presence of a constraint does not
> make a difference by itself. Does the difference here lie in
> compiler calls to fromFractional or fromIntegral in appropriate
> cases?

Yes.  The difference is that numeric literals are special -- they are
polymorphic.  3 has type (Num a) => a, and 3.14 has type (Fractional
a) => a.  So,

  f :: Fractional a => a

promises to be able to take on ANY fractional type, and sure enough,
3.14 can be any fractional type.  However,

  g :: Ord a => a

promises to be able to take on ANY Ord type, but True has type Bool,
which is too specific.  I should be able to write (for example)

  if g < 'x' then ... else ...

using g at type Char (since Char is an instance of Ord), but you can
easily see that this will not work if g = True.  Hence the error.

-Brent



More information about the Beginners mailing list