[Haskell-beginners] Why is type "Integer -> Integer" and not "(Num a) => a -> a"?

Chaddaï Fouché chaddai.fouche at gmail.com
Thu Nov 12 04:04:53 EST 2009


On Thu, Nov 12, 2009 at 9:37 AM, Dag Hovland <dag.hovland at uib.no> wrote:
> Hi!
>
> I have a problem with understanding some types given by ghc and hugs.
> The file loaded is:
>
> f1 = \x -> x * 2
> f2 x = x * 2
>
> After they are loaded I get the following from ghci
>
> *Main> :t f1
> f1 :: Integer -> Integer
> *Main> :t f2
> f2 :: (Num a) => a -> a
> *Main> :t \x -> x * 2
> \x -> x * 2 :: (Num a) => a -> a

This is called the monomorphism restriction, it's a rule that state a
binding _without_parameters_ shall be inferred of a monomorphic type
unless an explicit signature is given. There are several reasons for
it, some of efficiency (polymorphism has a cost) and some of a more
technical nature, refer to the Haskell Report for a more detailed
explanation.

Some Haskellers think this restriction is no longer required, that GHC
is now often intelligent enough to alleviate the cost of polymorphism,
that the technical reasons are not really all that pertinent and that
the default should be to infer the more general type in all case
rather than confuse beginners and oblige experts to put explicit
signatures. It is already possible to deactivate the restriction by
using the -XNoMonomorphismRestriction argument (or putting the
equivalent language pragma in the code itself or in the cabal
description file) and making this the default is discussed for
Haskell' (the future standard for Haskell).

In the meantime, it is a good idea to put ":set
-XNoMonomorphismRestriction" in your .ghci file since most usage of
GHCi would only hit the disadvantages of this rule and reap no
benefits from it.

-- 
Jedaï


More information about the Beginners mailing list