Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this typeclass only compile with "-XNoMonomorphismRestriction"?

I've been getting some strange typeclass errors of the form "No instance for (Test a0) arising from an expression type signature". Here is the simplest version of the offending code I could come up with:

class Test a where
  test :: a

foo = test

Adding the type doesn't help:

foo = test :: Test a => a

However, adding an instance of Test does make it compile:

instance Test Int where
  test = 0

This isn't really acceptable, as I want my instances declared elsewhere.

Finally, passing -XNoMonomorphismRestriction to ghc(i) also allows it to compile. While this is good enough for now, I don't understand what this extension does, why it is necessary, or what downsides may be lurking.

like image 637
Vlad Firoiu Avatar asked Dec 20 '22 11:12

Vlad Firoiu


1 Answers

As an alternative to disabling the monomorphism restriction for the whole file (which is fairly harmless, but can cause some unexpected recalculation of values that are not intended to be polymorphic), adding the type does help, but you have to do it as a signature at top level:

foo :: Test a => a
foo = test

If you add it just after test, it is considered just an annotation on the subexpression test, and does not turn off the monomorphism restriction for foo itself.

like image 72
Ørjan Johansen Avatar answered May 23 '23 08:05

Ørjan Johansen