将函数转换为无点样式会更改其类型
我正在开始 Haskell...我尝试用两种不同的方式编写以下简单函数,让 Haskell 决定类型,并且类型系统在每种情况下都会执行不同的操作。这种行为的解释是什么?
Prelude> let f x = 2 * x
Prelude> let g = (2*)
Prelude> :info f
f :: Num a => a -> a -- Defined at <interactive>:1:5
Prelude> :info g
g :: Integer -> Integer -- Defined at <interactive>:1:5
谢谢!
I'm beginning Haskell... I tried to write the following trivial function in two different ways, letting Haskell decide the types, and the type system does something different in each case. What is the explanation for that behavior?
Prelude> let f x = 2 * x
Prelude> let g = (2*)
Prelude> :info f
f :: Num a => a -> a -- Defined at <interactive>:1:5
Prelude> :info g
g :: Integer -> Integer -- Defined at <interactive>:1:5
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这称为单态限制。
基本上,这意味着看起来像
x =
的顶级绑定被迫是非多态的,除非您指定类型签名。带参数的绑定,即fx =
不受影响。有关为何存在此限制的详细信息,请参阅链接。通常,当应用限制时,您会收到一条错误消息,但在这种情况下,GHCi 能够使用默认类型来更改类型
Num a =>; a
到整数
。避免它的最简单方法是使用显式类型签名,或者放在
模块的顶部,或者使用
-XNoMonomorphismRestriction
运行 GHCi。This is known as the monomorphism restriction.
Basically, it means that top-level bindings that look like
x =
are forced to be non-polymorphic, unless you specify a type signature. Bindings with arguments, i.e.f x =
are not affected. See the link for details as to why this restriction exists.Usually, you get an error message when the restriction is applied, but in this case GHCi is able to use type defaulting to change the type
Num a => a
toInteger
.The easiest way to dodge it is to either use an explicit type signature, or put
at the top of your module, or run GHCi with
-XNoMonomorphismRestriction
.正如其他人指出的那样,这是由“单态限制”引起的。
MR 对于 Haskell 编译器的编写者来说很有用,但总体而言,对于该语言是否值得拥有 MR 存在争议。但有一点大家都同意:在 GHCi 提示下,MR 只不过是一种麻烦。
在即将推出的 GHC 版本中,在这种情况下,MR 可能会默认关闭。现在,您应该在 GHCi 中禁用它,方法是在您的主目录中创建一个名为“
.ghci
”的文本文件,其中包含如下行:As others have pointed out, this is caused by something called the "Monomorphism Restriction".
MR can be useful for writers of Haskell compilers, and there is controversy about whether or not it is worthwhile to have in the language in general. But there is one thing everyone agrees: at the GHCi prompt, MR is nothing but a nuisance.
MR will probably be turned off by default in this context in an upcoming version of GHC. For now, you should disable it in GHCi by creating a text file called "
.ghci
" in your home directory that contains a line like this:由于
g
的定义没有显式命名其参数,因此您会遇到 单态限制,防止g
成为多态并(在本例中)导致 GHC 默认为Integer
。Because the definition of
g
doesn't explicitly name its arguments, you run into the monomorphism restriction, preventingg
from being polymorphic and (in this case) causing GHC to default toInteger
.