为什么基本Prelude算法不需要显式类型? [英] Why is an explicit type NOT required for basic Prelude arithmetic?

查看:103
本文介绍了为什么基本Prelude算法不需要显式类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是回答问题并编写了一些代码来完成工作。

I was answering a question and wrote some code to get the job done.

isPrime :: Int -> Bool
isPrime n = primeCheck n $ floor $ sqrt $ (fromIntegral n :: Double)

我认为显式类型签名是必需的,正如我的回答中所解释的。然后我在GHC和GHCi中检查了它,发现尽管 floor 不需要明确的转换类型> sqrt 是多态的。我知道 GHCi会做某些类型的违约行为 a>,但我不知道任何GHC。显然, Float Double 在这里是有效的选择,为什么GHC选择一个呢?什么类型是默认的,为什么(假定)GHC在这种情况下是默认的?

I assumed that the explicit type signature would be required, as explained in my answer. Then I checked it in both GHC and GHCi and discovered that I did not need the explicit type for the conversion despite floor and sqrt being polymorphic. I know GHCi does does some type defaulting, but I'm not aware of any in GHC. Obviously both Float and Double would be valid choices here, why does GHC choose one over the other? What type is defaulted to, and why does (presumably) GHC default in this case?

推荐答案

GHC也会输入类型默认值,至少在你导出模块的时候,它会将任何不明确的数字类型单态化为类型为默认类型,默认为:

GHC does type type-defaulting as well, at least whenever you export a module it will monomorphize any ambiguous numeric types to the types in default types for the module, which is by defaulted to:

default (Integer, Double)

请参见4.3.4模糊类型和重载默认值数字操作中的 Haskell规范

See the section "4.3.4 Ambiguous Types, and Defaults for Overloaded Numeric Operations" in the Haskell specification.

您可以在要导出的模块中使用pragma { - #LANGUAGE NoMonomorphismRestriction# - } 顶级数字多态类型完好无损。

You can disable this with the pragma {-# LANGUAGE NoMonomorphismRestriction #-} in the module you want to export with toplevel numeric polymorphic types left intact.

这篇关于为什么基本Prelude算法不需要显式类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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