6

Learning Haskell, in ghci:

Prelude Data.Ratio> :type 0.15
0.15 :: Fractional a => a

Prelude Data.Ratio> 0.15
0.15
it :: Double

Why are types different? Are those two instances of 0.15 actually different types?

LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93
  • possible duplicate of [What is the monomorphism restriction?](http://stackoverflow.com/questions/32496864/what-is-the-monomorphism-restriction) – Bakuriu Sep 11 '15 at 09:08

1 Answers1

11

This due to the dreaded monomorphism restriction. Basically, GHCi likes to choose default types when executed (the default Fractional type is Double), but when you ask the type using :type it chooses the most general version. You can disable this behavior with the NoMonomorphismRestriction extension:

> :set -XNoMonomorphismRestriction
> :set +t
> 0.15
0.15
it :: Fractional a => a
> :t 0.15
0.15 :: Fractional a => a

While this this extension has one of the scarier names, it's rather simple when you break it down:

Mono  -> One
Morph -> shape (type)
ism   -> thingy
Monomorphism -> one shape thingy -> one type thingy -> thing with a single type

So basically it's a really long word that means "single type". Then with "restriction", you get that the monomorphism restriction is restricting things to a single type. In this case, it's restricting numbers (the things) to the type Double. Without this restriction, the type of the numbers is only constrained by a type class, which can in theory be an infinite number of types.

bheklilr
  • 53,530
  • 6
  • 107
  • 163
  • 6
    I note that even though it displays `it :: Fractional a => a`, it obviously needs to choose *some* type for evaluating and printing the actual result "`0.15`" (e.g. `0.15 :: Rational` is printed differently), so there is *some* defaulting and `Double` involved even with `NoMonomorphismRestriction`. – Ørjan Johansen May 29 '14 at 22:25
  • @ØrjanJohansen: that's a good point, although I'd guess that `:type` simply echos the entered string, in which case no defaulting is necessary. – John L May 29 '14 at 23:35
  • @JohnL Yes, I was referring to the two-line response to the `> 0.15` line in this answer. – Ørjan Johansen May 30 '14 at 01:41