[Haskell-cafe] a simple question about types

Daniel Fischer daniel.is.fischer at web.de
Wed Nov 17 13:31:28 EST 2010

On Wednesday 17 November 2010 19:09:16, Jerzy M wrote:
> Hallo,
> let me take this simple function: (2*).
> If I check its type
> :t (2*)
> I'll obtain
> (2*) :: (Num a) => a -> a
> But now it suffices to write
> g = (2*)
> and check
> :t g
> to obtain
> g :: Integer -> Integer
> One more combination, now I write
> h x = (2*) x
> and check once more
> :t h
> to get
> h :: (Num a) => a -> a
> So my question is: why (in this second example) Integer is inferred?
> What makes a difference?

The monomorphism restriction.
As specified in section 4.5.5 of the language report 
values bound by a (simple) pattern binding (basically, not bound by a 
binding with function arguments to the left of '=') which don't have 
explicit type signatures get a monomorphic type (ambiguous type variables 
are resolved per the defaulting rules of section 4.3 if possible).


g = (2*)

is a simple pattern binding without type signature, hence it gets a 
monomorphic type.
The inferred type is

g :: Num a => a -> a

and by the defaulting rules (unless you have an explicit default 
declaration in the module where g is defined), the ambiguous type variable 
a is resolved to Integer.

h x = (2*) x

is a function binding, hence h gets the inferred polymorphic type.

The MR is often inconvenient (it may be removed in future language 
standards, I'm not up to date with the standings of that proposal), so it 
can be disabled (at least in GHC).
In normal code, it's not so frequent a matter (on one hand, there's more 
context in the module than at the ghci prompt, on the other hand, modules 
contain more type signatures), so it's comparatively rare to need
{-# LANGUAGE NoMonomorphismRestriction #-}.
At the ghci prompt, however, it's a frequent cause of surprise, so it may 
be a good idea to put the line

:set -XNoMonomorphismRestriction

in your ~/.ghci file.


More information about the Haskell-Cafe mailing list