ghci-默认混乱 [英] ghci - defaulting confusion

查看:92
本文介绍了ghci-默认混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在检查不同整数类型的大小(minBoundmaxBound)和十进制表示的长度"时,我偶然发现一些奇怪的行为.

I happened to see some strange behaviour during checking the size (minBound,maxBound) and "length in decimal representation" of different integral types.

使用GHCi:

Prelude> :{
Prelude| let mi = minBound
Prelude|     ma = maxBound
Prelude|     le = fromIntegral $ length $ show ma
Prelude|  in [mi,ma,le] :: [Int]
Prelude| :}
[-9223372036854775808,922372036854775807,2]
                                         ^

最后一个我希望是19.

我的第一个猜测是maxBound默认为()并因此产生2,但是我不明白,因为ma应该是显式类型注释(:: [Int])的Int. -并且参照透明性,所有名为ma的符号都应相等.

My first guess is that maxBound defaults to () and thus yields 2, but I don't understand that because ma should be an Int by the explicit type annotation (:: [Int]) - and by referential transparency all symbols named ma should be equal.

如果将上面的语句放入文件中并将其加载到GHCi中,则会得到正确的结果.

If I put the statement above in a file and load it into GHCi, I get the correct result.

那我为什么会得到错误的结果?

So why do I get a wrong result?

推荐答案

令人困惑的是,这仍然是发挥作用的单态性限制(或者在GHCi中缺少这种限制).由于GHCi没有启用单态性限制,因此mima的定义不会像您认为的那样专门化为Int-而是将它们通用化为mi, ma :: Bounded a => aa变量实例化两次

Confusingly, this is still the monomorphism restriction at play (or rather the lack thereof when in GHCi). Since GHCi doesn't have the monomorphism restriction enabled, your definitions of mi and ma don't get specialized to Int as you think they will - instead they stay general as mi, ma :: Bounded a => a and the a variable gets instantiated twice

  • fromIntegral $ length $ show ma中一次作为()(如您所见,这是默认设置)
  • [mi,ma,le] :: [Int]中曾经作为Int
  • once as () in fromIntegral $ length $ show ma (as you observed, this is a default)
  • once as Int in [mi,ma,le] :: [Int]

如果您希望mima实际上是Int类型,请直接对其进行注释

If you want mi and ma to actually be of type Int, annotate them as such directly

Prelude> :{
Prelude| let mi, ma :: Int
Prelude|     mi = minBound
Prelude|     ma = maxBound
Prelude|     le = fromIntegral $ length $ show ma
Prelude|  in [mi,ma,le]
Prelude| :}
[-9223372036854775808,9223372036854775807,19]

或者在GHCi中手动打开单态限制

Or turn on the monormorphism restriction manually in GHCi

Prelude> :set -XMonomorphismRestriction
Prelude> :{
Prelude| let mi = minBound
Prelude|     ma = maxBound
Prelude|     le = fromIntegral $ length $ show ma
Prelude| in [mi,ma,le] :: [Int]
Prelude| :}
[-9223372036854775808,9223372036854775807,19]

这篇关于ghci-默认混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆