haskellmonomorphism-restriction

"Overloaded signature conflicts with monomorphism restriction"


Why is this allowed:

i :: Num a => a
i = 1

While none of these is allowed:

i' :: Num a => a
Just i' = Just 1

x, y :: Num a => a
(x, y) = (1, 2)

x :: Num a => a
y :: Num a => a
(x, y) = (1, 2)

y :: Num a => a
x :: Num a => a
(x, y) = (1, 2)

m :: ()
n :: Num a => a
(n, m) = (1, ())

n :: Num a => a
m :: ()
(n, m) = (1, ())

Unless turned off monomorphism restriction by {-# LANGUAGE NoMonomorphismRestriction #-}, trying to compile with any of them always results in "Overloaded signature conflicts with monomorphism restriction".

But haven't I already specified all the types here? How could the monomorphism restriction even come up in the first place?


Solution

  • Quoth the rule:

    We say that a given declaration group is unrestricted if and only if:
    (a): every variable in the group is bound by a function binding or a simple pattern binding (Section 4.4.3.2), and
    (b): an explicit type signature is given for every variable in the group that is bound by simple pattern binding.

    What is a simple pattern binding though? There are two contradictory definitions.

    (4.5.5 The Monomorphism Restriction) a simple pattern binding is a pattern binding in which the pattern consists of only a single variable

    and

    (4.4.3.2 Pattern bindings) A simple pattern binding has form p = e

    According to the first definition, none of your failed bindings are simple, so they cannot be unrestricted, which means the mononorphism restriction applies to them. According to the second definition, all are simple and unrestricted, that is, the mononorphism restriction should not apply.

    The applicable definition should be the first one as detailed in this posting and that's what the compiler is using, but AFAICT the report is not updated to reflect this.