3

This tiny Haskell program reads two space-separated numbers from console and prints their sum:

main = do
  line <- getLine
  let n1:n2:_ = map read $ words line
  print $ n1 + n2

I'd expect the compilation to fail because of ambiguity: + restricts the type of n1 and n2 to Num typeclass and not to a specific type. However GHC 7.10 successfully compiles it inferring Integer type (replacing + by / changes the inferred type to Double). What is the explanation for that?

Jason
  • 3,777
  • 14
  • 27
mstone
  • 414
  • 4
  • 11
  • 1
    I know the answer in the linked question mentions defaulting, but still marking the question as a duplicate of "What is the monomorphism restriction?" is misleading since the monomorphism restriction is not relevant here. – Reid Barton Nov 03 '15 at 15:45

1 Answers1

4

Haskell has a special case for dealing with the numeric classes (Num, Fractional and a few others) which picks a default type for ambiguous type variables. (See the 2010 report for more details.)

The way it works is by trying a series of numeric types until one satisfies all of the constraints. By default it first tries Integer and then Double, but you can also control this on a per-module basis:

default (Int, Rational)

If you want to turn defaulting off for your module, just don't give it any types:

default ()

Honestly, this is a big hack to make Haskell easier to use as a calculator. But it does make life quite a bit easier since we don't have to explicitly annotate the types of literals in programs like yours, which would also be confusing.

Tikhon Jelvis
  • 67,485
  • 18
  • 177
  • 214