[Haskell] Implicit type of numeric constants

Robert Stroud R.J.Stroud at ncl.ac.uk
Wed Sep 20 07:39:35 EDT 2006


Hello,

I'm a newcomer to Haskell and I've been typing some simple  
expressions into Hugs in an attempt to understand how the built-in  
numeric types work . However, I'm puzzled by the following example:

k = 2

f :: Int -> Int -> Int
f x y = x * y

After loading a file containing this code into Hugs, if I type "f 2  
2" I get the value 4 as expected, but if I type "f k k" I get a type  
error because the type of k is inferred to be Integer.

This seems like a violation of referential transparency to me - I  
would expect the inferred type of k to be the same as the type of 2.

However, if I type an apparently equivalent let expression into Hugs  
directly, then I get the value 4 as expected

let k = 2 ; f :: Int -> Int -> Int ; f x y = x * y in f k k

Why is there a difference in behaviour?

For that matter, if the type of 2 is "Num a => a", which I understand  
to mean "an arbitrary numeric type", why is it OK to pass 2 to a  
function that expects an Int?

Thank you.

Robert Stroud



More information about the Haskell mailing list