[Haskell-cafe] is monomorphism restriction necessary?

Roman Cheplyaka roma at ro-che.info
Sat Apr 16 15:49:15 UTC 2016


On 04/16/2016 02:53 PM, Alexey Muranov wrote:
> Sorry for the question that probably is already answered somewhere, but i do not get it from the basic documentation i have looked at so far.
> 
> Is monomorphism restriction really necessary, or is it just a convenience?
> 
> In the example from A History of Haskell
> 
>     genericLength :: Num a => [b] -> a
> 
>     f xs = (len, len)
>         where
>             len = genericLength xs
> 
> can't the monomorphism restriction be replaced with just adding the signature
> 
>     f :: Num a => [b] -> (a, a)
> 
> ?

No; the let binding 'len' would still generalize. It would generalize
even if you assigned 'f' a monotype such as [b] -> (Int, Int).

Now, the compiler *could* later realize that the polymorphic value 'len'
is evaluated twice at the same type and perform a CSE, but I guess the
standard authors were not comfortable with *requiring* that kind of
optimization from all compliant compilers.

Of course, nowadays we have scoped type variables, so MR is no longer
strictly necessary. Sometimes it is desirable in that it gives the
behavior that you would intuitively expect; sometimes, the opposite.

Roman


More information about the Haskell-Cafe mailing list