Inconsistent behavior with Integral in GHCi

I was hoping someone could explain the following behavior in GHCi using the fromIntegral function:

Prelude> let x = 1 :: Integer Prelude> :txx :: Integer Prelude> sqrt $ fromIntegral x 1.0 Prelude> let y = fromIntegral x Prelude> sqrt y <interactive>:181:1: No instance for (Floating Integer) arising from a use of `sqrt' Possible fix: add an instance declaration for (Floating Integer) In the expression: sqrt y In an equation for `it': it = sqrt y 

Why does it matter if I install y and then take it sqrt or just take sqrt ?

+4
source share
1 answer

fromIntegral is polymorphic in return type. So you can expect the type y in your code to be Num a => a . This type allows you to use y as the sqrt argument without any problems.

However, due to the restriction of monomorphism, the type y cannot be polymorphic. Therefore, the default is to use the default Num type, which is Integer .

If you execute sqrt $ fromIntegral x monomorphism restriction does not apply, since it applies only to global variables, and you do not save the fromIntegral result in a variable this time.

You can fix this problem by adding a type signature to y ( let y :: Num a => a; y = fromIntegal x ) or by disabling the monomorphism restriction.

+9
source

All Articles