[Haskell-cafe] Type Coercion

Thomas Davie tom.davie at gmail.com
Wed May 28 03:41:19 EDT 2008


On 28 May 2008, at 09:34, 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 coercion -- it happens at compile time.

In a coercion, 16 starts off it's runtime life as an integer, gets a  
couple of things done to it, and then is coerced into a floating point  
number.  What's happening here is you are telling the compiler "I  
would like the number 16, but a floating point version of it please".   
That instance of 16 always will have type Float.

Slightly more detail:  numeric literals like this normally have the  
type Int, but get pre-processed by the compiler.  Whenever you write  
16, the compiler writes (fromInteger 16).  This has the effect that  
instead of having the type Int, your literal has the type Num a => a.   
You adding the type signature constrains it to being a Float again.

Bob


More information about the Haskell-Cafe mailing list