[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: another take on hackers and painters

Bayley, Alistair writes:
> Umm... I might have misunderstood your point, but I think Haskell
> doesn't really do coercion. In general type conversions are
> explicit. For example,
> > x :: Int
> > x = 3.0
> will be rejected by the compiler (mine's GHC).
> > y :: Double
> > y = 3
> will be accepted, I suppose because 3 is good enough (but only as a
> literal) for Doubles.

What happens is that the Haskell compiler silently inserts a call to
fromInteger in front of the '3' -- this expression is the same as:

let y :: Double = fromInteger 3

Since Double is part of the Num typeclass, it provides an
implementation for the fromInteger overloaded function, and all this
works. The (+) function has type Num a => a -> a -> a, which means
that the two arguments have to be of the same type. But if add an
integer to another number, it will be coerced: 3 + 3.0 --> 6.0

Haskell is pretty conservative about the coercions it does, and I
agree that's usually a good idea. But I *love* not having to write a
separate version of a numeric function with the integral and floating
point versions; for example, the obvious definition of factorial will
work at all Num types, not just integers.

Neel Krishnaswami