20

I follow a bit the tag and I often see questions like:

All these question share the same answer:

It's the dreaded monomorphism restriction. Bindings of the type x = ... are forced to be monomorphic unless you provide a type signature.

You can disallow the behaviour by using the NoMonomorphismRestriction extension by putting:

{-# LANGUAGE NoMonomorphismRestriction #-}

at the top of your file or compiling with the flag -XNoMonomorphismRestriction.

I know that having the same answer doesn't imply that the questions are duplicate, yet looking at all those question I don't think that having many different answers and questions is a good thing.

What I see is that the information about the issue is spread across many different questions, which are generally very hard to search effectively, and the answer they obtain are fundamentally identical in their basic information, yet most answer miss some aspect or information that would be useful.

I propose to create (or find an existing) canonical question regarding the issue and provide a thorough answer (probably taking information and examples from the HaskellWiki) and close all other questions as duplicates of this one.

The next time a new question is asked where the answer would be "it's due to the monomorphism restriction + link to HaskellWiki", instead of answering vote to close as a duplicate of the canonical question.

In this way everyone will see the most complete and useful answer, instead of receive only part of the information about the issue.

I believe the canonical answer ought to:

  • explain what the monomorphism restriction is and when it is triggered (with a few examples, taken from the wiki or the linked questions above)
  • how to avoid it (type signatures, pragma and compilation flag)
  • difference between ghci and ghc
  • what changed with new versions of haskell and ghc/ghci

Reading at the answers and questions above I couldn't find any existing answer that contains all the above information.

18
  • It looks like you worked out most of the details needed for that post. What's keeping you from posting it?
    – Cerbrus
    Commented May 12, 2015 at 8:55
  • 5
    @Cerbrus Before doing it I'd like to hear at least some opinions from those who follow the tag. Having a canonical Q&A is useless if nobody is going to actually use it and reference it. Also, I believe there are people that would produce a better explanation than mine.
    – Bakuriu
    Commented May 12, 2015 at 8:58
  • 1
    Ah, that makes sense :-)
    – Cerbrus
    Commented May 12, 2015 at 8:59
  • 2
    You might consider making your current proposed canonical answer a community wiki answer to this meta question to more easily allow other collaboration. It also has the benefit of separating the meta votes for "I think we need a canonical Q&A" from the meta votes for "I think this answer is a good canonical answer"
    – ryanyuyu
    Commented Aug 26, 2015 at 21:30
  • 1
    @ryanyuyu Okay, I'm doing it now.
    – Bakuriu
    Commented Aug 27, 2015 at 6:41
  • "I know that having the same answer doesn't imply that the questions are duplicate ... I propose to create (or find an existing) canonical question ... and close all other questions as duplicates of this one." So you acknowledge that it isn't a duplicate yet you try to close other questions as being a duplicate? That sounds like abuse. As I mentioned in one of the questions you marked as a duplicate, the question you created presupposes that the asker already knows the answer to their question. Knowing what MR is doesn't make it obvious that it's the cause of your trouble when you run into it. Commented Sep 11, 2015 at 20:10
  • Questions should only be marked as duplicate if they actually are duplicates. In this case, what you should really be doing is adding a "See also" link to your "canonical answer" in each of the "It's the dreaded monomorphism restriction" answers (either in a comment or in an answer itself). Commented Sep 11, 2015 at 20:29
  • 1
    @LaurenceGonsalves You had 4 months to provide feedback here if you didn't agree. Moreover what I meant is that maybe not all of such questions could be considered duplicates but most are duplicates (just renaming a variable in the code or changing an Int to aDouble doesn't make your question not a duplicate). Moreover in all cases I believe that having a single pointer with all the information well organized is better than having to search for tens of different pointers and try to rearrange all information in your head.
    – Bakuriu
    Commented Sep 12, 2015 at 7:16
  • @LaurenceGonsalves Regarding your quesiton: that's exactly what I'd call a perfect duplicate. Besides the answer is one of the least helpful I found, barely stating the name of the issue and mentioning how to turn the restriction off without any sort of explanation. Note that if you read carefully the answer I posted you'll find that it answer all the points in your question.
    – Bakuriu
    Commented Sep 12, 2015 at 7:18
  • 1
    @LaurenceGonsalves Final point: I'm a bit offended that you say this is an "abuse". As I already mentioned I opened this meta question before posting that question&answer. I did so 4 months ago and I asked if somebody (not me) would do that. People told me "just do it yourself". I've repeteadly asked on chat etc for feedback and all the feedback I got was "go ahead, that's good stuff". Moreover note that I don't have a dupe-hammer for haskell so I can only provide one close vote. If people disagree the question wont be closed. No harm done (plus this already adds the link).
    – Bakuriu
    Commented Sep 12, 2015 at 7:21
  • Are you really trying to say that the fact that you posted this 4 months ago means it's too late for people to criticize your plan now? I'm feeling a bit like Arthur Dent here. You had far longer to mark many of those questions as duplicates (sometimes years) so by your own reasoning it's too late for you to complain about them now. Commented Sep 13, 2015 at 22:10
  • Many of the questions you attempted to close as duplicate (including mine) aren't duplicates of your question at all, because the questions don't even know that MR is a factor. A question cannot duplicate a separate question that presupposes the answer. It's like if you went to the doctor and started telling her your symptoms and she cuts you off and says "just tell me what you've got and I'll tell you the treatment". The question should discuss only symptoms and the answer then provides diagnosis and treatment. Commented Sep 13, 2015 at 22:11
  • Do you think it would make sense for someone to post a question "What is Haskell?" along with a copy of The Haskell 98 Language Report as an answer, and then close every question that could be answered by a careful reading of the report (including your question "What is the monomorphism restriction?") as a duplicate? What you're doing isn't far off from that. Commented Sep 13, 2015 at 22:12
  • If you really want to consolidate the MR questions, a better approach would be to group the questions that are similar, and post a generalized question for each group. I feel like I'm restating the obvious here, but the monomorphism restriction should not even be mentioned in the question, as that presupposes the answer. Only the answer should talk about MR. If you want to have the answers to these questions link to your "What is the monomorphism restriction?" question, then that sounds great. Commented Sep 13, 2015 at 22:12
  • @LaurenceGonsalves I didn't say that it's too late. Just that you cannot come here without reading anything and accuse me of abuse. I also disagree with your reasoning. To me the case of MR is the same as (e.g.) "the mutable default argument in python". The question is simply missing the formal name. What happens in that case is that whenever someone post the millionth question with a def f(x=[]) it is "insta-closed" to avoid that people loose time answer that when all the information is already on SO.
    – Bakuriu
    Commented Sep 14, 2015 at 6:28

2 Answers 2

4

I've posted the question & a modified version of the below answer at: What is the monomorphism restriction?


I took some time to draft a possible answer. I'd like to have any inputs on it.

  • Is there anything missing or wrong in it?
  • Is there some unclear passage?
  • Should I add something else? While the answer should satisfy new users giving also a high level description of the problem and how to fix it, I also want to provide an in-depth explanation for those who want to understand what's at work. I'm even considering adding a bit of explanation about unification and how type inferencing is done so that readers can really get a feeling of what's happening. Would this be too much?

If there's already an answer that contains the information above I'd like to know about it, so that we can use that instead (and eventually improve it).

I made this answer CW as suggested so that you can more easily edit it. Feel free to provide your improvements. If this answer receive some attention and upvotes in the ~next week (say till 6 September) I'll post it as a CW question & answer.


What is the monomorphism restriction?

The monomorphism restriction as stated by the Haskell wiki is:

a counter-intuitive rule in Haskell type inference. If you forget to provide a type signature, sometimes this rule will fill the free type variables with specific types using "type defaulting" rules.

What this means is that, in some circumstances, if your type is ambiguous (i.e. polymorphic) the compiler will choose to instantiate that type to something not ambiguous.

An example

Take the following trivial definition:

plus = (+)

you'd think to be able to replace every occurrence of + with plus. In particular since (+) :: Num a => a -> a -> a you'd expect to also have plus :: Num a => a -> a -> a.

Unfortunately this is not the case. For example in we try the following in GHCi:

Prelude> let plus = (+)
Prelude> plus 1.0 1

We get the following output:

<interactive>:4:6:
    No instance for (Fractional Integer) arising from the literal ‘1.0’
    In the first argument of ‘plus’, namely ‘1.0’
    In the expression: plus 1.0 1
    In an equation for ‘it’: it = plus 1.0 1

You may need to :set -XMonomorphismRestriction in newer GHCi versions.

And in fact we can see that the type of plus is not what we would expect:

Prelude> :t plus
plus :: Integer -> Integer -> Integer

What happened is that the compiler saw that plus had type Num a => a -> a -> a, a polymorphic type. Moreover it happens that the above definition falls under the rules that I'll explain later and so he decided to make the type monomorphic by defaulting the type variable a. The default is Integer as we can see.

Some other example

Consider the following definitions:

f1 x = show x

f2 = \x -> show x

f3 :: (Show a) => a -> String
f3 = \x -> show x

f4 = show

f5 :: (Show a) => a -> String
f5 = show

We'd expect all these functions to behave in the same way and have the same type, i.e. the type of show: Show a => a -> String.

Yet:

  • f1 is okay.
  • f2 has type () -> String.
  • f3 is okay.
  • f4 has again type () -> String
  • f5 is okay.

Monomorphism restriction is what makes f2 and f4 have that strange type. If you have declarations like the f2 and f4 or plus in your program you'll probably have some trouble with this restriction.

Note that this last example isn't actually Haskell 2010 compliant. According to the Haskell 2010 report only numeric types can be defaulted and so you'd get a type error instead of a defaulting to ().

How do I fix it?

First of all you can always explicitly provide a type signature and this will avoid the triggering of the restriction:

plus :: Num a => a -> a -> a
plus = (+)    -- Okay!

-- Runs as:
Prelude> plus 1.0 1
2.0

Alternatively, if you are defining a function, you can avoid point-free style, and for example write:

plus x y = x + y

Turning it off

It is possible to simply turn off the restriction so that you don't have to do anything to your code to fix it. The behaviour is controlled by two extensions: MonomorphismRestriction will enable it (which is the default) while NoMonomorphismRestriction will disable it.

You can put the following line at the very top of your file:

{-# LANGUAGE NoMonomorphismRestriction #-}

If you are using GHCi you can enable the extension using the :set command:

Prelude> :set -XNoMonomorphismRestriction

You can also tell ghc to enable the extension from the command line:

ghc ... -XNoMonomorphismRestriction

Note: You should really prefer the first option over choosing extension via command-line options.

Refer to GHC's page for an explanation of this and other extensions.

When does it happen?

In Haskell, as defined by the report, there are two distinct type of bindings. Function bindings and pattern bindings. A function binding is nothing else than a definition of a function:

f x = x + 1

Note that their syntax is:

<identifier> arg1 arg2 ... argn = expr

Modulo guards and where declarations. But they don't really matter.

where there must be at least one argument.

A pattern binding is a declaration of the form:

<pattern> = expr

Again, modulo guards.

Note that variables are patterns, so the binding:

plus = (+)

is a pattern binding. It's binding the pattern plus (a variable) to the expression (+).

When a pattern binding consists of only a variable name it's called a simple pattern binding.

The monomorphism restriction applies to simple pattern bindings!

Well, formally we should say that:

A declaration group is a minimal set of mutually dependent bindings.

Section 4.5.1 of the report.

And then (Section 4.5.5 of the report):

a given declaration group is unrestricted if and only if:

  1. every variable in the group is bound by a function binding (e.g. f x = x) or a simple pattern binding (e.g. plus = (+); Section 4.4.3.2 ), and

  2. an explicit type signature is given for every variable in the group that is bound by simple pattern binding. (e.g. plus :: Num a => a -> a -> a; plus = (+)).

Examples added by me.

So a restricted declaration group is a group where, either there are non-simple pattern bindings (e.g. (x:xs) = f something or (f, g) = ((+), (-))) or there is some simple pattern binding without a type signature (as in plus = (+)).

The monomorphism restriction affects restricted declaration groups.

Most of the time you don't define mutual recursive functions and hence a declaration group becomes just a binding.

What does it do?

The monomorphism restriction is described by two rules in Section 4.5.5 of the report.

First rule

The usual Hindley-Milner restriction on polymorphism is that only type variables that do not occur free in the environment may be generalized. In addition, the constrained type variables of a restricted declaration group may not be generalized in the generalization step for that group. (Recall that a type variable is constrained if it must belong to some type class; see Section 4.5.2 .)

The highlighted part is what the monomorphism restriction introduces. It says that if the type is polymorphic (i.e. it contain some type variable) and that type variable is constrained (i.e. it has a class constraint on it: e.g. the type Num a => a -> a -> a is polymorphic because it contains a and also contrained because the a has the constraint Num over it.) then it cannot be generalized.

In simple words not generalizing means that the uses of the function plus may change its type.

If you had the definitions:

plus = (+)

x :: Integer
x = plus 1 2

y :: Double
y = plus 1.0 2

then you'd get a type error. Because when the compiler sees that plus is called over an Integer in the declaration of x it will unify the type variable a with Integer and hence the type of plus becomes:

Integer -> Integer -> Integer

but then, when it will type check the definition of y, it will see that plus is applied to a Double argument, and the types don't match.

Note that you can still use plus without getting an error:

plus = (+)
x = plus 1.0 2

In this case the type of plus is first inferred to be Num a => a -> a -> a but then its use in the definition of x, where 1.0 requires a Fractional constraint, will change it to Fractional a => a -> a -> a.

Rationale

The report says:

Rule 1 is required for two reasons, both of which are fairly subtle.

  • Rule 1 prevents computations from being unexpectedly repeated. For example, genericLength is a standard function (in library Data.List) whose type is given by

    genericLength :: Num a => [b] -> a
    

    Now consider the following expression:

    let len = genericLength xs
    in (len, len)
    

    It looks as if len should be computed only once, but without Rule 1 it might be computed twice, once at each of two different overloadings. If the programmer does actually wish the computation to be repeated, an explicit type signature may be added:

    let len :: Num a => a
        len = genericLength xs
    in (len, len)
    

For this point the example from the wiki is, I believe, clearer. Consider the function:

f xs = (len, len)
  where
    len = genericLength xs

If len was polymorphic the type of f would be:

f :: Num a, Num b => [c] -> (a, b)

So the two elements of the tuple (len, len) could actually be different values! But this means that the computation done by genericLength must be repeated to obtain the two different values.

The rationale here is: the code contains one function call, but not introducing this rule could produce two hidden function calls, which is counter intuitive.

With the monomorphism restriction the type of f becomes:

f :: Num a => [b] -> (a, a)

In this way there is no need to perform the computation multiple times.

  • Rule 1 prevents ambiguity. For example, consider the declaration group

    [(n,s)] = reads t

    Recall that reads is a standard function whose type is given by the signature

    reads :: (Read a) => String -> [(a,String)]

    Without Rule 1, n would be assigned the type ∀ a. Read a ⇒ a and s the type ∀ a. Read a ⇒ String. The latter is an invalid type, because it is inherently ambiguous. It is not possible to determine at what overloading to use s, nor can this be solved by adding a type signature for s. Hence, when non-simple pattern bindings are used (Section 4.4.3.2 ), the types inferred are always monomorphic in their constrained type variables, irrespective of whether a type signature is provided. In this case, both n and s are monomorphic in a.

Well, I believe this example is self-explanatory. There are situations when not applying the rule results in type ambiguity.

If you disable the extension as suggest above you will get a type error when trying to compile the above declaration. However this isn't really a problem: you already know that when using read you have to somehow tell the compiler which type it should try to parse...

Second rule

  1. Any monomorphic type variables that remain when type inference for an entire module is complete, are considered ambiguous, and are resolved to particular types using the defaulting rules (Section 4.3.4 ).

This means that. If you have your usual definition:

plus = (+)

This will have a type Num a => a -> a -> a where a is a monomorphic type variable due to rule 1 described above. Once the whole module is inferred the compiler will simply choose a type that will replace that a according to the defaulting rules.

The final result is: plus :: Integer -> Integer -> Integer.

Note that this is done after the whole module is inferred.

This means that if you have the following declarations:

plus = (+)

x = plus 1.0 2.0

inside a module, before type defaulting the type of plus will be: Fractional a => a -> a -> a (see rule 1 for why this happens). At this point, following the defaulting rules, a will be replaced by Double and so we will have plus :: Double -> Double -> Double and x :: Double.

Defaulting

As stated before there exist some defaulting rules, described in Section 4.3.4 of the Report, that the inferencer can adopt and that will replace a polymorphic type with a monomorphic one. This happens whenever a type is ambiguous.

For example in the expression:

let x = read "<something>" in show x

here the expression is ambiguous because the types for show and read are:

show :: Show a => a -> String
read :: Read a => String -> a

So the x has type Read a => a. But this constraint is satisfied by a lot of types: Int, Double or () for example. Which one to choose? There's nothing that can tell us.

In this case we can resolve the ambiguity by telling the compiler which type we want, adding a type signature:

let x = read "<something>" :: Int in show x

Now the problem is: since Haskell uses the Num type class to handle numbers, there are a lot of cases where numerical expressions contain ambiguities.

Consider:

show 1

What should the result be?

As before 1 has type Num a => a and there are many type of numbers that could be used. Which one to choose?

Having a compiler error almost every time we use a number isn't a good thing, and hence the defaulting rules were introduced. The rules can be controlled using a default declaration. By specifying default (T1, T2, T3) we can change how the inferencer defaults the different types.

An ambiguous type variable v is defaultable if:

  • v appears only in contraints of the kind C v were C is a class (i.e. if it appears as in: Monad (m v) then it is not defaultable).
  • at least one of these classes is Num or a subclass of Num.
  • all of these classes are defined in the Prelude or a standard library.

A defaultable type variable is replaced by the first type in the default list that is an instance of all the ambiguous variable’s classes.

The default default declaration is default (Integer, Double).

For example:

plus = (+)
minus = (-)

x = plus 1.0 1
y = minus 2 1

The types inferred would be:

plus :: Fractional a => a -> a -> a
minus :: Num a => a -> a -> a

which, by defaulting rules, become:

plus :: Double -> Double -> Double
minus :: Integer -> Integer -> Integer

Extended defaulting

Note that GHCi comes with extended defaulting rules, which can be enabled in files as well using the ExtendedDefaultRules extensions.

The defaultable type variables need not only appear in contraints where all the classes are standard and there must be at least one class that is among Eq, Ord, Show or Num and its subclasses.

Moreover the default default declaration is default ((), Integer, Double).

Useful links

There are a lot of resources and discussions about the monomorphism restriction.

Here are some links that I find useful and that may help you understand or deep further into the topic:

1

I don't believe all of these questions should be considered duplicates. I think the question is not a duplicate when:

  • the monomorphism restriction is applied when a user function's type is related to a non-trivial type from a library in such a way that it is not immediately obvious what the correct type is, and
  • the library in question is a commonly-used one which is being used in a common way, and therefore other users are likely to see an identical error

In such a case the correct answer is to indicate what type signature is required, along with a clarification that this is required due to the monomorphism restriction and preferably a link to the canonical answer above. See Trivial parsec example produces a type error for an example of such a question.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .