Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top