为什么是“(2 + 2.0)”?双.hs文件,但“分数a =>一个"在GHCi? [英] Why is "(2+2.0)" Double in a .hs file but "Fractional a => a" in GHCi?
问题描述
.hs
文件加载 a = 2 + 2.0
并执行 :ta
显示 a :: Double
。 另一方面, GHCi中的code> let b = 2 + 2.0 和:tb
显示 b ::小数a => ;一个
。
你怎么能从这两个文件中推断出这个?
我发现这个官方文档几乎不可理解。
本文档是您想要的,我想。基本上,GHC在GHCi中默认实现与模块中不同的语言;特别是,可怕的单态限制在模块中是默认启用的(按照语言),而在GHCi中它是禁用的。单态的约束是什么导致GHC为你的 a
选择一个单形类型,而在关闭时,GHC可以自由地概括 b
,产生你看到的多态类型。
Loading a = 2+2.0
from a .hs
file in GHCi and doing :t a
shows a :: Double
.
On the other hand, doing let b = 2+2.0
and :t b
in GHCi shows b :: Fractional a => a
.
How are you able to deduce this from these two documents?
- 4.3.4 Ambiguous Types, and Defaults for Overloaded Numeric Operations https://www.haskell.org/onlinereport/haskell2010/haskellch4.html#x10-750004.3
- 2.4.8 Type defaulting in GHCi: https://downloads.haskell.org/~ghc/7.8.3/docs/html/users_guide/interactive-evaluation.html
I find this official documentation almost incomprehensible.
This documentation is what you want, I think. Basically, GHC implements a different language by default in GHCi than in a module; in particular, the dreaded monomorphism restriction is enabled by default in a module (as per the language) whereas in GHCi it's disabled. The monomorphism restriction is what causes GHC to pick a monomorphic type for your a
, whereas, with it turned off, GHC is free to generalize the type of b
, yielding the polymorphic type you see.
这篇关于为什么是“(2 + 2.0)”?双.hs文件,但“分数a =>一个"在GHCi?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!