GHCI显示为具体的类型

发布于 2025-01-23 01:10:48 字数 462 浏览 2 评论 0原文

我有以下代码:

{-# 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

优雅的叶子 2025-01-30 01:10:48

此行为是由单态限制在源文件中启用,但在GHCI中被禁用。

基本上,规则是,没有参数的变量绑定总是推断为具有具体类型。在您的情况下,绑定g = float'1.2没有参数,因此在推断类型时,它是num约束将默认为整数。

如果您添加虚拟参数,则可以看到行为会发生变化:

g () = Float' 1.2

或者只是禁用单态限制:

{-# LANGUAGE NoMonomorphismRestriction #-}

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's Num constraint will be defaulted to Integer when inferring types.

You can see that the behavior changes if you add a dummy argument:

g () = Float' 1.2

Or if you just disable the monomorphism restriction:

{-# LANGUAGE NoMonomorphismRestriction #-}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文