GHCI显示为具体的类型
我有以下代码:
{-# LANGUAGE GADTs #-}
data Exp' a where
Float' :: (Num a) => Float -> Exp' a
g = Float' 1.2
如果将上述代码直接键入ghci
,并检查g
的类型,我会得到:
GHCI> let g = Float' 1.2
GHCI> :t g
g :: Num a => Exp' a
以上是我所期望的。
但是,当使用上述代码加载文件时,我会得到这个:
GHCI> :load <filename>
GHCI> :t g
g :: Exp' Integer
任何想法为什么行为是不同的?提前致谢。
I have the following code:
{-# LANGUAGE GADTs #-}
data Exp' a where
Float' :: (Num a) => Float -> Exp' a
g = Float' 1.2
If I type the above code directly into ghci
, and check g
's type, I'd get:
GHCI> let g = Float' 1.2
GHCI> :t g
g :: Num a => Exp' a
The above is what I expected.
However, when loading a file with the above code, I'd get this instead:
GHCI> :load <filename>
GHCI> :t g
g :: Exp' Integer
Any idea why the behaviors are different? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行为是由单态限制在源文件中启用,但在GHCI中被禁用。
基本上,规则是,没有参数的变量绑定总是推断为具有具体类型。在您的情况下,绑定
g = float'1.2
没有参数,因此在推断类型时,它是num
约束将默认为整数。如果您添加虚拟参数,则可以看到行为会发生变化:
或者只是禁用单态限制:
This behavior is caused by the monomorphism restriction which is enabled in source files, but disabled in GHCi.
Basically, the rule is that variable bindings without arguments are always inferred to have a concrete type. In your case the binding
g = Float' 1.2
doesn't have arguments, so it'sNum
constraint will be defaulted to Integer when inferring types.You can see that the behavior changes if you add a dummy argument:
Or if you just disable the monomorphism restriction: