is -fno-monomorphism-restriction evil?

Matthew Danish mdanish at andrew.cmu.edu
Tue Oct 9 16:58:11 EDT 2007


On Tue, Oct 09, 2007 at 03:29:55PM -0300, Jorge Marques Pelizzoni wrote:
> It may be a side-effect of being a newbie, but many times I find the
> -fno-monomorphism-restriction quite handy. Is it intrinsically evil? I
> mean, has anyone had a bad time using it or does it imply some runtime
> performance overhead? I guess it is not portable, is it?

The worst that can happen is unexpected repeated computation.  This
arises because type-class constraints on polymorphism act like a
"hidden parameter" to a function.  In bindings of the form:

var = ...

you may have expected that the value of var is only computed once.
However, if the type of var is polymorphic with type-class
constraints, then it is "really" a function.

var dictionary = ...

where the dictionary is a parameter which supplies the method
definitions for whichever type is being used.

Simple example, a function which reverses the parameters of the method
"compare" of the "Ord" type-class:

f = flip compare

This turns into

f ordDict = flip (compare ordDict)

and now instead of being a simple variable binding it could be
recomputed each time it is used.

There are 3 ways to address this issue:

1) explicit parameters: the restriction only applies to bindings of
the form "var = ...", so if it's really a function, make those
parameters explicit.

f x y = compare y x

2) explicit type annotation: the restriction is lifted if you give an
explicit type annotation.

f :: Ord a => a -> a -> Ordering
f = flip compare

3) -fno-monomorphism-restriction and equivalents

Is -fno-monomorphism-restriction "evil"?  No, I don't think so.  I
think there is some debate on whether the whole restriction should be
lifted for Haskell' even.

As for portability, you can now use:

{-# LANGUAGE NoMonomorphismRestriction #-}

at the top of your file.  This should be more "portable" than a
ghc-specific compiler option.  See the GHC manual section on pragmas
for the full details.

-- 
-- Matthew Danish -- user: mrd domain: cmu.edu
-- OpenPGP public key: C24B6010 on keyring.debian.org


More information about the Glasgow-haskell-users mailing list