在GHCi中与来自整体的行为不一致 [英] Inconsistent behavior with fromIntegral in GHCi
问题描述
Prelude>>我希望有人能够在GHCi中解释以下行为:让x = 1 :: Integer
Prelude> :t x
x :: Integer
Prelude> sqrt $ fromIntegral x
1.0
Prelude>让y = fromIntegral x
Prelude> sqrt y
< interactive>:181:1:
使用`sqrt'引起的(浮点整数)
没有实例
可能的修正:添加(Floating Integer)
的实例声明在表达式:sqrt y中
在'it'的等式中:it = sqrt y
为什么重要我设置了 y
,然后取其 sqrt
或直接使用 sqrt
? 因此,代码中的 y
类型可以预期为 Num a =>一个
。这种类型允许您在没有问题的情况下使用 y
作为 sqrt
的参数。
然而,由于单态的限制, y
的类型不允许为多态。因此它默认为默认的Num类型,它是 Integer
。
当您执行 你可以通过向y添加一个类型签名来解决这个问题( I was hoping someone could explain the following behavior in GHCi, when using the function fromIntegral: Why does it matter whether I set However due to the monomorphism restriction, the type of When you do You can fix this issue by either adding a type signature to y ( 这篇关于在GHCi中与来自整体的行为不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! sqrt $ fromIntegral x
单态限制并不适用,因为它仅适用于全局变量,并且不会将
let y :: Num a => a; y = fromIntegal x
)或禁用单态限制。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
y
and then take its sqrt
or just directly take the sqrt
? fromIntegral
is polymorphic in its return type. So the type of y
in your code could be expected to be Num a => a
. This type would allow you to use y
as the argument to sqrt
without problem.y
is not allowed to be polymorphic. Therefore it is defaulted to the default Num type, which is Integer
.sqrt $ fromIntegral x
the monomorphism restriction does not apply because it only applies to global variables and you don't store the result of fromIntegral
in a variable this time.let y :: Num a => a; y = fromIntegal x
) or by disabling the monomorphism restriction.