[Haskell-cafe] Type Coercion

Andrew Coppin andrewcoppin at btinternet.com
Wed May 28 14:36:40 EDT 2008

PR Stanley wrote:
> Hi
> (16 :: Float) is a perfectly legitimate statement although I'm 
> surprised that it's allowed in a type strong language such as Haskell. 
> It's a bit like casting in good old C. What's going on here?

It's not a type cast, it's a class method:

class Num n where
  fromInteger :: Integer -> n

The literal "16" is interpretted as the function call "fromInteger 16". 
If you write a literal, the compiler will usually optimise away the 
function call leaving only a literal Float/Double/Int/Word16/whatever.

Notice, however, that you can explicitly call this function yourself at 
any time to change the type of something. Note that this is *not* a type 
cast. It doesn't just change what type the type checker thinks the data 
is; it really does change the actual bit pattern in memory. (E.g., 
turning an Integer into a Word8, possibly causing the value to overflow 
and wrap around in the process!)

It's really no more mysterious than the way "show" can transform many 
kinds of data into a String, and "read" can transform them back again. 
It's not bypassing the type system, it's doing a real type conversion.

I hope that made sense...

More information about the Haskell-Cafe mailing list