Why is an explicit type NOT required for basic Pre

2019-02-22 04:20发布

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)

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?

标签: haskell ghc
2条回答
祖国的老花朵
2楼-- · 2019-02-22 05:03

I'm guessing the default keyword?

It allows you to specify what to use when no signature is given. There is also a "default" default, which is Double.

I forget exactly how all of this works; it's a rather obscure corner of the language...

查看更多
3楼-- · 2019-02-22 05:04

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)

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

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

查看更多
登录 后发表回答