I was hoping someone could explain the following behavior in GHCi, when using the function fromIntegral:
Prelude> let x = 1 :: Integer
Prelude> :t x
x :: 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 whether I set y and then take its sqrt or just directly take the sqrt?
fromIntegralis polymorphic in its return type. So the type ofyin your code could be expected to beNum a => a. This type would allow you to useyas the argument tosqrtwithout problem.However due to the monomorphism restriction, the type of
yis not allowed to be polymorphic. Therefore it is defaulted to the default Num type, which isInteger.When you do
sqrt $ fromIntegral xthe monomorphism restriction does not apply because it only applies to global variables and you don’t store the result offromIntegralin a variable this time.You can fix this issue by either adding a type signature to y (
let y :: Num a => a; y = fromIntegal x) or by disabling the monomorphism restriction.